blob: 6a860760732d57a2a10af5421f13faafa2319484 [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;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070057import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070059import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080062import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070063
Christopher Tated55e18a2009-09-21 10:12:59 -070064import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070065import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070067import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070068
Christopher Tatecde87f42009-06-12 12:55:53 -070069import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070070import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080072import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070073import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070074import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070075import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040077import java.util.ArrayList;
78import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070079import java.util.HashSet;
80import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070081import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070082import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080083import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070084
85class BackupManagerService extends IBackupManager.Stub {
86 private static final String TAG = "BackupManagerService";
Chris Tatea9c50432010-10-11 14:37:12 -070087 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070088
Christopher Tate49401dd2009-07-01 12:34:29 -070089 // How often we perform a backup pass. Privileged external callers can
90 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070091 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070092
Dan Egnorc1c49c02009-10-30 17:35:39 -070093 // Random variation in backup scheduling time to avoid server load spikes
94 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
95
Christopher Tate8031a3d2009-07-06 16:36:05 -070096 // The amount of time between the initial provisioning of the device and
97 // the first backup pass.
98 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
99
Christopher Tate45281862010-03-05 15:46:30 -0800100 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
101 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
102 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700103 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700104 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700105 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700106 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700107 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700108 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
109 private static final int MSG_TIMEOUT = 7;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700110
111 // Timeout interval for deciding that a bind or clear-data has taken too long
112 static final long TIMEOUT_INTERVAL = 10 * 1000;
113
Christopher Tate44a27902010-01-27 17:15:49 -0800114 // Timeout intervals for agent backup & restore operations
115 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
116 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
117
Christopher Tate487529a2009-04-29 14:03:25 -0700118 private Context mContext;
119 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800120 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700121 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700122 private PowerManager mPowerManager;
123 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800124 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700125
Christopher Tate73e02522009-07-15 14:18:26 -0700126 boolean mEnabled; // access to this is synchronized on 'this'
127 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800128 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700129 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800130 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
131 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700132 PendingIntent mRunBackupIntent, mRunInitIntent;
133 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700134 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700135 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700137 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700138 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700139 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700140 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate181fafa2009-05-14 11:12:14 -0700142 BackupRequest(ApplicationInfo app, boolean isFull) {
143 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700144 fullBackup = isFull;
145 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700146
147 public String toString() {
148 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
149 }
Christopher Tate46758122009-05-06 11:22:00 -0700150 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400151 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700152 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700153 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700154
155 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700156 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700157
158 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700159 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700160
Christopher Tate043dadc2009-06-02 16:11:00 -0700161 // The thread performing the sequence of queued backups binds to each app's agent
162 // in succession. Bind notifications are asynchronously delivered through the
163 // Activity Manager; use this lock object to signal when a requested binding has
164 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700165 final Object mAgentConnectLock = new Object();
166 IBackupAgent mConnectedAgent;
167 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700168 volatile long mLastBackupPass;
169 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700170
Christopher Tate55f931a2009-09-29 17:17:34 -0700171 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700172 final Object mClearDataLock = new Object();
173 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700174
Christopher Tate91717492009-06-26 21:07:13 -0700175 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700176 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700177 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700178 String mCurrentTransport;
179 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800180 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700181
Christopher Tate2d449afe2010-03-29 19:14:24 -0700182 class RestoreGetSetsParams {
183 public IBackupTransport transport;
184 public ActiveRestoreSession session;
185 public IRestoreObserver observer;
186
187 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
188 IRestoreObserver _observer) {
189 transport = _transport;
190 session = _session;
191 observer = _observer;
192 }
193 }
194
Christopher Tate73e02522009-07-15 14:18:26 -0700195 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700196 public IBackupTransport transport;
197 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700198 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800199 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800200 public int pmToken; // in post-install restore, the PM's token for this transaction
Christopher Tate84725812010-02-04 15:52:40 -0800201
202 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Christopher Tate1bb69062010-02-19 17:02:12 -0800203 long _token, PackageInfo _pkg, int _pmToken) {
Christopher Tate84725812010-02-04 15:52:40 -0800204 transport = _transport;
205 observer = _obs;
206 token = _token;
207 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800208 pmToken = _pmToken;
Christopher Tate84725812010-02-04 15:52:40 -0800209 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700210
Dan Egnor156411d2009-06-26 13:20:02 -0700211 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700212 transport = _transport;
213 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700214 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800215 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800216 pmToken = 0;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700217 }
218 }
219
Christopher Tate73e02522009-07-15 14:18:26 -0700220 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700221 public IBackupTransport transport;
222 public PackageInfo packageInfo;
223
224 ClearParams(IBackupTransport _transport, PackageInfo _info) {
225 transport = _transport;
226 packageInfo = _info;
227 }
228 }
229
Christopher Tate44a27902010-01-27 17:15:49 -0800230 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
231 // token is the index of the entry in the pending-operations list.
232 static final int OP_PENDING = 0;
233 static final int OP_ACKNOWLEDGED = 1;
234 static final int OP_TIMEOUT = -1;
235
236 final SparseIntArray mCurrentOperations = new SparseIntArray();
237 final Object mCurrentOpLock = new Object();
238 final Random mTokenGenerator = new Random();
239
Christopher Tate5cb400b2009-06-25 16:03:14 -0700240 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700241 File mBaseStateDir;
242 File mDataDir;
243 File mJournalDir;
244 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700245
Christopher Tate84725812010-02-04 15:52:40 -0800246 // Keep a log of all the apps we've ever backed up, and what the
247 // dataset tokens are for both the current backup dataset and
248 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700249 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700250 HashSet<String> mEverStoredApps = new HashSet<String>();
251
Christopher Tateb49ceb32010-02-08 16:22:24 -0800252 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800253 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800254 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800255 long mAncestralToken = 0;
256 long mCurrentToken = 0;
257
Christopher Tate4cc86e12009-09-21 19:36:51 -0700258 // Persistently track the need to do a full init
259 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
260 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700261
Christopher Tate44a27902010-01-27 17:15:49 -0800262 // ----- Asynchronous backup/restore handler thread -----
263
264 private class BackupHandler extends Handler {
265 public BackupHandler(Looper looper) {
266 super(looper);
267 }
268
269 public void handleMessage(Message msg) {
270
271 switch (msg.what) {
272 case MSG_RUN_BACKUP:
273 {
274 mLastBackupPass = System.currentTimeMillis();
275 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
276
277 IBackupTransport transport = getTransport(mCurrentTransport);
278 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800280 mWakelock.release();
281 break;
282 }
283
284 // snapshot the pending-backup set and work on that
285 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800286 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800287 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800288 // Do we have any work to do? Construct the work queue
289 // then release the synchronization lock to actually run
290 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800291 if (mPendingBackups.size() > 0) {
292 for (BackupRequest b: mPendingBackups.values()) {
293 queue.add(b);
294 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800295 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800296 mPendingBackups.clear();
297
298 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800299 mJournal = null;
300
Christopher Tate44a27902010-01-27 17:15:49 -0800301 }
302 }
Christopher Tatec61da312010-02-05 10:41:27 -0800303
304 if (queue.size() > 0) {
305 // At this point, we have started a new journal file, and the old
306 // file identity is being passed to the backup processing thread.
307 // When it completes successfully, that old journal file will be
308 // deleted. If we crash prior to that, the old journal is parsed
309 // at next boot and the journaled requests fulfilled.
310 (new PerformBackupTask(transport, queue, oldJournal)).run();
311 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800312 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800313 mWakelock.release();
314 }
Christopher Tate44a27902010-01-27 17:15:49 -0800315 break;
316 }
317
318 case MSG_RUN_FULL_BACKUP:
319 break;
320
321 case MSG_RUN_RESTORE:
322 {
323 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800324 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800325 (new PerformRestoreTask(params.transport, params.observer,
Christopher Tate1bb69062010-02-19 17:02:12 -0800326 params.token, params.pkgInfo, params.pmToken)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800327 break;
328 }
329
330 case MSG_RUN_CLEAR:
331 {
332 ClearParams params = (ClearParams)msg.obj;
333 (new PerformClearTask(params.transport, params.packageInfo)).run();
334 break;
335 }
336
337 case MSG_RUN_INITIALIZE:
338 {
339 HashSet<String> queue;
340
341 // Snapshot the pending-init queue and work on that
342 synchronized (mQueueLock) {
343 queue = new HashSet<String>(mPendingInits);
344 mPendingInits.clear();
345 }
346
347 (new PerformInitializeTask(queue)).run();
348 break;
349 }
350
Christopher Tate2d449afe2010-03-29 19:14:24 -0700351 case MSG_RUN_GET_RESTORE_SETS:
352 {
353 // Like other async operations, this is entered with the wakelock held
354 RestoreSet[] sets = null;
355 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
356 try {
357 sets = params.transport.getAvailableRestoreSets();
358 // cache the result in the active session
359 synchronized (params.session) {
360 params.session.mRestoreSets = sets;
361 }
362 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
363 } catch (Exception e) {
364 Slog.e(TAG, "Error from transport getting set list");
365 } finally {
366 if (params.observer != null) {
367 try {
368 params.observer.restoreSetsAvailable(sets);
369 } catch (RemoteException re) {
370 Slog.e(TAG, "Unable to report listing to observer");
371 } catch (Exception e) {
372 Slog.e(TAG, "Restore observer threw", e);
373 }
374 }
375
376 mWakelock.release();
377 }
378 break;
379 }
380
Christopher Tate44a27902010-01-27 17:15:49 -0800381 case MSG_TIMEOUT:
382 {
383 synchronized (mCurrentOpLock) {
384 final int token = msg.arg1;
385 int state = mCurrentOperations.get(token, OP_TIMEOUT);
386 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800387 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800388 mCurrentOperations.put(token, OP_TIMEOUT);
389 }
390 mCurrentOpLock.notifyAll();
391 }
392 break;
393 }
394 }
395 }
396 }
397
398 // ----- Main service implementation -----
399
Christopher Tate487529a2009-04-29 14:03:25 -0700400 public BackupManagerService(Context context) {
401 mContext = context;
402 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700403 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700404 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700405
Christopher Tateb6787f22009-07-02 17:40:45 -0700406 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
407 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
408
Christopher Tate44a27902010-01-27 17:15:49 -0800409 mBackupManagerBinder = asInterface(asBinder());
410
411 // spin up the backup/restore handler thread
412 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
413 mHandlerThread.start();
414 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
415
Christopher Tate22b87872009-05-04 16:41:53 -0700416 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700417 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700418 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700419 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700420 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800421 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800422 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800423 // If Encrypted file systems is enabled or disabled, this call will return the
424 // correct directory.
425 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
426 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700427 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700428
Christopher Tate4cc86e12009-09-21 19:36:51 -0700429 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700430 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700431 IntentFilter filter = new IntentFilter();
432 filter.addAction(RUN_BACKUP_ACTION);
433 context.registerReceiver(mRunBackupReceiver, filter,
434 android.Manifest.permission.BACKUP, null);
435
436 mRunInitReceiver = new RunInitializeReceiver();
437 filter = new IntentFilter();
438 filter.addAction(RUN_INITIALIZE_ACTION);
439 context.registerReceiver(mRunInitReceiver, filter,
440 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700441
442 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700443 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
444 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
445
Christopher Tate4cc86e12009-09-21 19:36:51 -0700446 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
447 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
448 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
449
Christopher Tatecde87f42009-06-12 12:55:53 -0700450 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700451 mJournalDir = new File(mBaseStateDir, "pending");
452 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700453 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700454
Christopher Tate73e02522009-07-15 14:18:26 -0700455 // Set up the various sorts of package tracking we do
456 initPackageTracking();
457
Christopher Tateabce4e82009-06-18 18:35:32 -0700458 // Build our mapping of uid to backup client services. This implicitly
459 // schedules a backup pass on the Package Manager metadata the first
460 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700461 synchronized (mBackupParticipants) {
462 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700463 }
464
Dan Egnor87a02bc2009-06-17 02:30:10 -0700465 // Set up our transport options and initialize the default transport
466 // TODO: Have transports register themselves somehow?
467 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700468 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700469 ComponentName localName = new ComponentName(context, LocalTransport.class);
470 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700471
Christopher Tate91717492009-06-26 21:07:13 -0700472 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700473 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
474 Settings.Secure.BACKUP_TRANSPORT);
475 if ("".equals(mCurrentTransport)) {
476 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700477 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800478 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700479
480 // Attach to the Google backup transport. When this comes up, it will set
481 // itself as the current transport because we explicitly reset mCurrentTransport
482 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700483 ComponentName transportComponent = new ComponentName("com.google.android.backup",
484 "com.google.android.backup.BackupTransportService");
485 try {
486 // If there's something out there that is supposed to be the Google
487 // backup transport, make sure it's legitimately part of the OS build
488 // and not an app lying about its package name.
489 ApplicationInfo info = mPackageManager.getApplicationInfo(
490 transportComponent.getPackageName(), 0);
491 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
492 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
493 Intent intent = new Intent().setComponent(transportComponent);
494 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
495 } else {
496 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
497 }
498 } catch (PackageManager.NameNotFoundException nnf) {
499 // No such package? No binding.
500 if (DEBUG) Slog.v(TAG, "Google transport not present");
501 }
Christopher Tateaa088442009-06-16 18:25:46 -0700502
Christopher Tatecde87f42009-06-12 12:55:53 -0700503 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700504 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700505 parseLeftoverJournals();
506
Christopher Tateb6787f22009-07-02 17:40:45 -0700507 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700508 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700509
510 // Start the backup passes going
511 setBackupEnabled(areEnabled);
512 }
513
514 private class RunBackupReceiver extends BroadcastReceiver {
515 public void onReceive(Context context, Intent intent) {
516 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700517 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700518 if (mPendingInits.size() > 0) {
519 // If there are pending init operations, we process those
520 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800521 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700522 try {
523 mAlarmManager.cancel(mRunInitIntent);
524 mRunInitIntent.send();
525 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800526 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700527 // can't really do more than bail here
528 }
529 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800530 // Don't run backups now if we're disabled or not yet
531 // fully set up.
532 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800533 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700534
535 // Acquire the wakelock and pass it to the backup thread. it will
536 // be released once backup concludes.
537 mWakelock.acquire();
538
539 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
540 mBackupHandler.sendMessage(msg);
541 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800542 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700543 }
544 }
545 }
546 }
547 }
548 }
549
550 private class RunInitializeReceiver extends BroadcastReceiver {
551 public void onReceive(Context context, Intent intent) {
552 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
553 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800554 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700555
556 // Acquire the wakelock and pass it to the init thread. it will
557 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700558 mWakelock.acquire();
559
Christopher Tate4cc86e12009-09-21 19:36:51 -0700560 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700561 mBackupHandler.sendMessage(msg);
562 }
563 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700564 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700565 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700566
Christopher Tate73e02522009-07-15 14:18:26 -0700567 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800568 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700569
Christopher Tate84725812010-02-04 15:52:40 -0800570 // Remember our ancestral dataset
571 mTokenFile = new File(mBaseStateDir, "ancestral");
572 try {
573 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800574 int version = tf.readInt();
575 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
576 mAncestralToken = tf.readLong();
577 mCurrentToken = tf.readLong();
578
579 int numPackages = tf.readInt();
580 if (numPackages >= 0) {
581 mAncestralPackages = new HashSet<String>();
582 for (int i = 0; i < numPackages; i++) {
583 String pkgName = tf.readUTF();
584 mAncestralPackages.add(pkgName);
585 }
586 }
587 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800588 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800589 } catch (FileNotFoundException fnf) {
590 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800591 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800592 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800593 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800594 }
595
Christopher Tatee97e8072009-07-15 16:45:50 -0700596 // Keep a log of what apps we've ever backed up. Because we might have
597 // rebooted in the middle of an operation that was removing something from
598 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700599 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700600 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700601
Christopher Tatee97e8072009-07-15 16:45:50 -0700602 // If we were in the middle of removing something from the ever-backed-up
603 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700604 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700605 if (tempProcessedFile.exists()) {
606 tempProcessedFile.delete();
607 }
608
Dan Egnor852f8e42009-09-30 11:20:45 -0700609 // If there are previous contents, parse them out then start a new
610 // file to continue the recordkeeping.
611 if (mEverStored.exists()) {
612 RandomAccessFile temp = null;
613 RandomAccessFile in = null;
614
615 try {
616 temp = new RandomAccessFile(tempProcessedFile, "rws");
617 in = new RandomAccessFile(mEverStored, "r");
618
619 while (true) {
620 PackageInfo info;
621 String pkg = in.readUTF();
622 try {
623 info = mPackageManager.getPackageInfo(pkg, 0);
624 mEverStoredApps.add(pkg);
625 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800626 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700627 } catch (NameNotFoundException e) {
628 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800629 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700630 }
631 }
632 } catch (EOFException e) {
633 // Once we've rewritten the backup history log, atomically replace the
634 // old one with the new one then reopen the file for continuing use.
635 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800636 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700637 }
638 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800639 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700640 } finally {
641 try { if (temp != null) temp.close(); } catch (IOException e) {}
642 try { if (in != null) in.close(); } catch (IOException e) {}
643 }
644 }
645
Christopher Tate73e02522009-07-15 14:18:26 -0700646 // Register for broadcasts about package install, etc., so we can
647 // update the provider list.
648 IntentFilter filter = new IntentFilter();
649 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
650 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
651 filter.addDataScheme("package");
652 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800653 // Register for events related to sdcard installation.
654 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800655 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
656 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800657 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700658 }
659
Christopher Tatecde87f42009-06-12 12:55:53 -0700660 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700661 for (File f : mJournalDir.listFiles()) {
662 if (mJournal == null || f.compareTo(mJournal) != 0) {
663 // This isn't the current journal, so it must be a leftover. Read
664 // out the package names mentioned there and schedule them for
665 // backup.
666 RandomAccessFile in = null;
667 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400668 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700669 in = new RandomAccessFile(f, "r");
670 while (true) {
671 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400672 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700673 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700674 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700675 } catch (EOFException e) {
676 // no more data; we're done
677 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800678 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700679 } finally {
680 // close/delete the file
681 try { if (in != null) in.close(); } catch (IOException e) {}
682 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700683 }
684 }
685 }
686 }
687
Christopher Tate4cc86e12009-09-21 19:36:51 -0700688 // Maintain persistent state around whether need to do an initialize operation.
689 // Must be called with the queue lock held.
690 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800691 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692 + " on transport " + transportName);
693 try {
694 IBackupTransport transport = getTransport(transportName);
695 String transportDirName = transport.transportDirName();
696 File stateDir = new File(mBaseStateDir, transportDirName);
697 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
698
699 if (isPending) {
700 // We need an init before we can proceed with sending backup data.
701 // Record that with an entry in our set of pending inits, as well as
702 // journaling it via creation of a sentinel file.
703 mPendingInits.add(transportName);
704 try {
705 (new FileOutputStream(initPendingFile)).close();
706 } catch (IOException ioe) {
707 // Something is badly wrong with our permissions; just try to move on
708 }
709 } else {
710 // No more initialization needed; wipe the journal and reset our state.
711 initPendingFile.delete();
712 mPendingInits.remove(transportName);
713 }
714 } catch (RemoteException e) {
715 // can't happen; the transport is local
716 }
717 }
718
Christopher Tated55e18a2009-09-21 10:12:59 -0700719 // Reset all of our bookkeeping, in response to having been told that
720 // the backend data has been wiped [due to idle expiry, for example],
721 // so we must re-upload all saved settings.
722 void resetBackupState(File stateFileDir) {
723 synchronized (mQueueLock) {
724 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700725 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700726 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700727
Christopher Tate84725812010-02-04 15:52:40 -0800728 mCurrentToken = 0;
729 writeRestoreTokens();
730
Christopher Tated55e18a2009-09-21 10:12:59 -0700731 // Remove all the state files
732 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700733 // ... but don't touch the needs-init sentinel
734 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
735 sf.delete();
736 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700737 }
738
739 // Enqueue a new backup of every participant
740 int N = mBackupParticipants.size();
741 for (int i=0; i<N; i++) {
742 int uid = mBackupParticipants.keyAt(i);
743 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
744 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700745 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700746 }
747 }
748 }
749 }
750
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800751 // Add a transport to our set of available backends. If 'transport' is null, this
752 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700753 private void registerTransport(String name, IBackupTransport transport) {
754 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800755 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800756 if (transport != null) {
757 mTransports.put(name, transport);
758 } else {
759 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800760 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800761 mCurrentTransport = null;
762 }
763 // Nothing further to do in the unregistration case
764 return;
765 }
Christopher Tate91717492009-06-26 21:07:13 -0700766 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700767
768 // If the init sentinel file exists, we need to be sure to perform the init
769 // as soon as practical. We also create the state directory at registration
770 // time to ensure it's present from the outset.
771 try {
772 String transportName = transport.transportDirName();
773 File stateDir = new File(mBaseStateDir, transportName);
774 stateDir.mkdirs();
775
776 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
777 if (initSentinel.exists()) {
778 synchronized (mQueueLock) {
779 mPendingInits.add(transportName);
780
781 // TODO: pick a better starting time than now + 1 minute
782 long delay = 1000 * 60; // one minute, in milliseconds
783 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
784 System.currentTimeMillis() + delay, mRunInitIntent);
785 }
786 }
787 } catch (RemoteException e) {
788 // can't happen, the transport is local
789 }
Christopher Tate91717492009-06-26 21:07:13 -0700790 }
791
Christopher Tate3799bc22009-05-06 16:13:56 -0700792 // ----- Track installation/removal of packages -----
793 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
794 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800795 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700796
Christopher Tate3799bc22009-05-06 16:13:56 -0700797 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800798 boolean replacing = false;
799 boolean added = false;
800 Bundle extras = intent.getExtras();
801 String pkgList[] = null;
802 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
803 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
804 Uri uri = intent.getData();
805 if (uri == null) {
806 return;
807 }
808 String pkgName = uri.getSchemeSpecificPart();
809 if (pkgName != null) {
810 pkgList = new String[] { pkgName };
811 }
812 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
813 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800814 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800815 added = true;
816 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800817 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800818 added = false;
819 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
820 }
821 if (pkgList == null || pkgList.length == 0) {
822 return;
823 }
824 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700825 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800826 for (String pkgName : pkgList) {
827 if (replacing) {
828 // The package was just upgraded
829 updatePackageParticipantsLocked(pkgName);
830 } else {
831 // The package was just added
832 addPackageParticipantsLocked(pkgName);
833 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700834 }
835 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800836 } else {
837 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700838 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
839 } else {
840 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800841 for (String pkgName : pkgList) {
842 removePackageParticipantsLocked(pkgName);
843 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700844 }
845 }
846 }
847 }
848 };
849
Dan Egnor87a02bc2009-06-17 02:30:10 -0700850 // ----- Track connection to GoogleBackupTransport service -----
851 ServiceConnection mGoogleConnection = new ServiceConnection() {
852 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700854 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700855 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700856 }
857
858 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800859 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700860 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700861 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700862 }
863 };
864
Christopher Tate181fafa2009-05-14 11:12:14 -0700865 // Add the backup agents in the given package to our set of known backup participants.
866 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700867 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700868 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800869 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700870 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700871 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700872 }
873
Christopher Tate181fafa2009-05-14 11:12:14 -0700874 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700875 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700876 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700878 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800879 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700880 + " uid=" + p.applicationInfo.uid
881 + " killAfterRestore="
882 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700883 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700884 }
885 }
886
Dan Egnorefe52642009-06-24 00:16:33 -0700887 for (PackageInfo pkg : targetPkgs) {
888 if (packageName == null || pkg.packageName.equals(packageName)) {
889 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700890 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700891 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700892 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700893 mBackupParticipants.put(uid, set);
894 }
Dan Egnorefe52642009-06-24 00:16:33 -0700895 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700896
897 // If we've never seen this app before, schedule a backup for it
898 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800899 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700900 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700901 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700902 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700903 }
Christopher Tate487529a2009-04-29 14:03:25 -0700904 }
905 }
906
Christopher Tate6785dd82009-06-18 15:58:25 -0700907 // Remove the given package's entry from our known active set. If
908 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700909 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700911 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700912 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700913 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700914 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700915 int flags = PackageManager.GET_SIGNATURES;
916 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700917 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700918 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700919 }
920 } else {
921 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700922 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700923 }
924 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700925 }
926
Joe Onorato8ad02812009-05-13 01:41:44 -0400927 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700928 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700929 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800930 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700931 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700932 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800933 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700934 }
935 }
Dan Egnorefe52642009-06-24 00:16:33 -0700936 for (PackageInfo pkg : agents) {
937 if (packageName == null || pkg.packageName.equals(packageName)) {
938 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700939 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700940 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700941 // Find the existing entry with the same package name, and remove it.
942 // We can't just remove(app) because the instances are different.
943 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700944 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700945 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700946 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700947 break;
948 }
949 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700950 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700951 mBackupParticipants.delete(uid);
952 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700953 }
954 }
955 }
956 }
957
Christopher Tate181fafa2009-05-14 11:12:14 -0700958 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700959 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700960 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700961 int flags = PackageManager.GET_SIGNATURES;
962 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
963 int N = packages.size();
964 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700965 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700966 try {
967 ApplicationInfo app = pkg.applicationInfo;
968 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800969 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700970 packages.remove(a);
971 }
972 else {
973 // we will need the shared library path, so look that up and store it here
974 app = mPackageManager.getApplicationInfo(pkg.packageName,
975 PackageManager.GET_SHARED_LIBRARY_FILES);
976 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
977 }
978 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700979 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700980 }
981 }
Dan Egnorefe52642009-06-24 00:16:33 -0700982 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700983 }
Christopher Tateaa088442009-06-16 18:25:46 -0700984
Christopher Tate3799bc22009-05-06 16:13:56 -0700985 // Reset the given package's known backup participants. Unlike add/remove, the update
986 // action cannot be passed a null package name.
987 void updatePackageParticipantsLocked(String packageName) {
988 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700990 return;
991 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800992 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700993
994 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700995 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700996 removePackageParticipantsLockedInner(packageName, allApps);
997 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700998 }
999
Christopher Tate84725812010-02-04 15:52:40 -08001000 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001001 // backed up at least once
1002 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001003 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1004
1005 synchronized (mEverStoredApps) {
1006 if (!mEverStoredApps.add(packageName)) return;
1007
1008 RandomAccessFile out = null;
1009 try {
1010 out = new RandomAccessFile(mEverStored, "rws");
1011 out.seek(out.length());
1012 out.writeUTF(packageName);
1013 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001014 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001015 } finally {
1016 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001017 }
1018 }
1019 }
1020
Christopher Tatee97e8072009-07-15 16:45:50 -07001021 // Remove our awareness of having ever backed up the given package
1022 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001023 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001024
Dan Egnor852f8e42009-09-30 11:20:45 -07001025 synchronized (mEverStoredApps) {
1026 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1027 // we'll recognize on initialization time that the package no longer
1028 // exists and fix it up then.
1029 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1030 RandomAccessFile known = null;
1031 try {
1032 known = new RandomAccessFile(tempKnownFile, "rws");
1033 mEverStoredApps.remove(packageName);
1034 for (String s : mEverStoredApps) {
1035 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001036 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001037 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001038 known.close();
1039 known = null;
1040 if (!tempKnownFile.renameTo(mEverStored)) {
1041 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1042 }
1043 } catch (IOException e) {
1044 // Bad: we couldn't create the new copy. For safety's sake we
1045 // abandon the whole process and remove all what's-backed-up
1046 // state entirely, meaning we'll force a backup pass for every
1047 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001048 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001049 mEverStoredApps.clear();
1050 tempKnownFile.delete();
1051 mEverStored.delete();
1052 } finally {
1053 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001054 }
1055 }
1056 }
1057
Christopher Tateb49ceb32010-02-08 16:22:24 -08001058 // Persistently record the current and ancestral backup tokens as well
1059 // as the set of packages with data [supposedly] available in the
1060 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001061 void writeRestoreTokens() {
1062 try {
1063 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001064
1065 // First, the version number of this record, for futureproofing
1066 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1067
1068 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001069 af.writeLong(mAncestralToken);
1070 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001071
1072 // Now write the set of ancestral packages
1073 if (mAncestralPackages == null) {
1074 af.writeInt(-1);
1075 } else {
1076 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001077 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001078 for (String pkgName : mAncestralPackages) {
1079 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001080 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001081 }
1082 }
Christopher Tate84725812010-02-04 15:52:40 -08001083 af.close();
1084 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001085 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001086 }
1087 }
1088
Dan Egnor87a02bc2009-06-17 02:30:10 -07001089 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001090 private IBackupTransport getTransport(String transportName) {
1091 synchronized (mTransports) {
1092 IBackupTransport transport = mTransports.get(transportName);
1093 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001094 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001095 }
1096 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001097 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001098 }
1099
Christopher Tatedf01dea2009-06-09 20:45:02 -07001100 // fire off a backup agent, blocking until it attaches or times out
1101 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1102 IBackupAgent agent = null;
1103 synchronized(mAgentConnectLock) {
1104 mConnecting = true;
1105 mConnectedAgent = null;
1106 try {
1107 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001109
1110 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001111 // only wait 10 seconds for the clear data to happen
1112 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1113 while (mConnecting && mConnectedAgent == null
1114 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001115 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001116 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001117 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001118 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001119 return null;
1120 }
1121 }
1122
1123 // if we timed out with no connect, abort and move on
1124 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001125 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001126 return null;
1127 }
1128 agent = mConnectedAgent;
1129 }
1130 } catch (RemoteException e) {
1131 // can't happen
1132 }
1133 }
1134 return agent;
1135 }
1136
Christopher Tatec7b31e32009-06-10 15:49:30 -07001137 // clear an application's data, blocking until the operation completes or times out
1138 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001139 // Don't wipe packages marked allowClearUserData=false
1140 try {
1141 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1142 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001143 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001144 + packageName);
1145 return;
1146 }
1147 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001148 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001149 return;
1150 }
1151
Christopher Tatec7b31e32009-06-10 15:49:30 -07001152 ClearDataObserver observer = new ClearDataObserver();
1153
1154 synchronized(mClearDataLock) {
1155 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001156 try {
1157 mActivityManager.clearApplicationUserData(packageName, observer);
1158 } catch (RemoteException e) {
1159 // can't happen because the activity manager is in this process
1160 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001161
1162 // only wait 10 seconds for the clear data to happen
1163 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1164 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1165 try {
1166 mClearDataLock.wait(5000);
1167 } catch (InterruptedException e) {
1168 // won't happen, but still.
1169 mClearingData = false;
1170 }
1171 }
1172 }
1173 }
1174
1175 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001176 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001177 synchronized(mClearDataLock) {
1178 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001179 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001180 }
1181 }
1182 }
1183
Christopher Tate1bb69062010-02-19 17:02:12 -08001184 // Get the restore-set token for the best-available restore set for this package:
1185 // the active set if possible, else the ancestral one. Returns zero if none available.
1186 long getAvailableRestoreToken(String packageName) {
1187 long token = mAncestralToken;
1188 synchronized (mQueueLock) {
1189 if (mEverStoredApps.contains(packageName)) {
1190 token = mCurrentToken;
1191 }
1192 }
1193 return token;
1194 }
1195
Christopher Tate44a27902010-01-27 17:15:49 -08001196 // -----
1197 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1198 boolean waitUntilOperationComplete(int token) {
1199 int finalState = OP_PENDING;
1200 synchronized (mCurrentOpLock) {
1201 try {
1202 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1203 try {
1204 mCurrentOpLock.wait();
1205 } catch (InterruptedException e) {}
1206 }
1207 } catch (IndexOutOfBoundsException e) {
1208 // the operation has been mysteriously cleared from our
1209 // bookkeeping -- consider this a success and ignore it.
1210 }
1211 }
1212 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001213 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001214 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001215 return finalState == OP_ACKNOWLEDGED;
1216 }
1217
1218 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001219 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001220 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001221 mCurrentOperations.put(token, OP_PENDING);
1222 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1223 mBackupHandler.sendMessageDelayed(msg, interval);
1224 }
1225
Christopher Tate043dadc2009-06-02 16:11:00 -07001226 // ----- Back up a set of applications via a worker thread -----
1227
Christopher Tate44a27902010-01-27 17:15:49 -08001228 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001229 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001230 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001231 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001232 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001233 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001234
Christopher Tate44a27902010-01-27 17:15:49 -08001235 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001236 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001237 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001238 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001239 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001240
1241 try {
1242 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1243 } catch (RemoteException e) {
1244 // can't happen; the transport is local
1245 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001246 }
1247
Christopher Tate043dadc2009-06-02 16:11:00 -07001248 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001249 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001250 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001251 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001252
Christopher Tate79588342009-06-30 16:11:49 -07001253 // Backups run at background priority
1254 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1255
Christopher Tate043dadc2009-06-02 16:11:00 -07001256 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001257 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001258
Dan Egnor852f8e42009-09-30 11:20:45 -07001259 // If we haven't stored package manager metadata yet, we must init the transport.
1260 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1261 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001262 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001263 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001264 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001265 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001266 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001267 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001268 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001269 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001270 }
Dan Egnor01445162009-09-21 17:04:05 -07001271 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001272
1273 // The package manager doesn't have a proper <application> etc, but since
1274 // it's running here in the system process we can just set up its agent
1275 // directly and use a synthetic BackupRequest. We always run this pass
1276 // because it's cheap and this way we guarantee that we don't get out of
1277 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001278 if (status == BackupConstants.TRANSPORT_OK) {
1279 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1280 mPackageManager, allAgentPackages());
1281 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1282 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1283 status = processOneBackup(pmRequest,
1284 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1285 }
Christopher Tate90967f42009-09-20 15:28:33 -07001286
Dan Egnor01445162009-09-21 17:04:05 -07001287 if (status == BackupConstants.TRANSPORT_OK) {
1288 // Now run all the backups in our queue
1289 status = doQueuedBackups(mTransport);
1290 }
1291
1292 if (status == BackupConstants.TRANSPORT_OK) {
1293 // Tell the transport to finish everything it has buffered
1294 status = mTransport.finishBackup();
1295 if (status == BackupConstants.TRANSPORT_OK) {
1296 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001297 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001298 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001299 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001301 }
1302 }
1303
Dan Egnor01445162009-09-21 17:04:05 -07001304 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001305 // The backend reports that our dataset has been wiped. We need to
1306 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001307 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001308 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001309 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001310 }
1311 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001312 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001313 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001314 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001315 // If everything actually went through and this is the first time we've
1316 // done a backup, we can now record what the current backup dataset token
1317 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001318 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001319 try {
1320 mCurrentToken = mTransport.getCurrentRestoreSet();
1321 } catch (RemoteException e) { /* cannot happen */ }
1322 writeRestoreTokens();
1323 }
1324
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001325 // If things went wrong, we need to re-stage the apps we had expected
1326 // to be backing up in this pass. This journals the package names in
1327 // the current active pending-backup file, not in the we are holding
1328 // here in mJournal.
1329 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001330 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001331 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001332 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001333 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001334
1335 // We also want to reset the backup schedule based on whatever
1336 // the transport suggests by way of retry/backoff time.
1337 try {
1338 startBackupAlarmsLocked(mTransport.requestBackupTime());
1339 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001340 }
1341
1342 // Either backup was successful, in which case we of course do not need
1343 // this pass's journal any more; or it failed, in which case we just
1344 // re-enqueued all of these packages in the current active journal.
1345 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001346 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001347 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001348 }
1349
Christopher Tatec2af5d32010-02-02 15:18:58 -08001350 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001351 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001352 backupNow();
1353 }
1354
Dan Egnorbb9001c2009-07-27 12:20:13 -07001355 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001356 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001357 }
1358
Dan Egnor01445162009-09-21 17:04:05 -07001359 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001360 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001361 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001362
1363 IBackupAgent agent = null;
1364 int mode = (request.fullBackup)
1365 ? IApplicationThread.BACKUP_MODE_FULL
1366 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1367 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001368 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001369 agent = bindToAgentSynchronous(request.appInfo, mode);
1370 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001371 int result = processOneBackup(request, agent, transport);
1372 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001373 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001374 } catch (SecurityException ex) {
1375 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001376 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001377 } finally {
1378 try { // unbind even on timeout, just in case
1379 mActivityManager.unbindBackupAgent(request.appInfo);
1380 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001381 }
1382 }
Dan Egnor01445162009-09-21 17:04:05 -07001383
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001384 mWakelock.setWorkSource(null);
1385
Dan Egnor01445162009-09-21 17:04:05 -07001386 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001387 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001388
Dan Egnor01445162009-09-21 17:04:05 -07001389 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1390 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001391 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001392 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001393
Dan Egnorbb9001c2009-07-27 12:20:13 -07001394 File savedStateName = new File(mStateDir, packageName);
1395 File backupDataName = new File(mDataDir, packageName + ".data");
1396 File newStateName = new File(mStateDir, packageName + ".new");
1397
1398 ParcelFileDescriptor savedState = null;
1399 ParcelFileDescriptor backupData = null;
1400 ParcelFileDescriptor newState = null;
1401
1402 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001403 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001404 try {
1405 // Look up the package info & signatures. This is first so that if it
1406 // throws an exception, there's no file setup yet that would need to
1407 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001408 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1409 // The metadata 'package' is synthetic
1410 packInfo = new PackageInfo();
1411 packInfo.packageName = packageName;
1412 } else {
1413 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001414 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001415 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001416
Christopher Tatec7b31e32009-06-10 15:49:30 -07001417 // In a full backup, we pass a null ParcelFileDescriptor as
1418 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001419 if (!request.fullBackup) {
1420 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001421 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001422 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1423 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001424
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 backupData = ParcelFileDescriptor.open(backupDataName,
1426 ParcelFileDescriptor.MODE_READ_WRITE |
1427 ParcelFileDescriptor.MODE_CREATE |
1428 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001429
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430 newState = ParcelFileDescriptor.open(newStateName,
1431 ParcelFileDescriptor.MODE_READ_WRITE |
1432 ParcelFileDescriptor.MODE_CREATE |
1433 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001434
Christopher Tate44a27902010-01-27 17:15:49 -08001435 // Initiate the target's backup pass
1436 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1437 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1438 boolean success = waitUntilOperationComplete(token);
1439
1440 if (!success) {
1441 // timeout -- bail out into the failed-transaction logic
1442 throw new RuntimeException("Backup timeout");
1443 }
1444
Dan Egnorbb9001c2009-07-27 12:20:13 -07001445 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001446 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001447 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001448 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001449 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001450 backupDataName.delete();
1451 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001452 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001453 } finally {
1454 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1455 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1456 try { if (newState != null) newState.close(); } catch (IOException e) {}
1457 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001458 synchronized (mCurrentOpLock) {
1459 mCurrentOperations.clear();
1460 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001461 }
1462
1463 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001464 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001465 try {
1466 int size = (int) backupDataName.length();
1467 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001468 if (result == BackupConstants.TRANSPORT_OK) {
1469 backupData = ParcelFileDescriptor.open(backupDataName,
1470 ParcelFileDescriptor.MODE_READ_ONLY);
1471 result = transport.performBackup(packInfo, backupData);
1472 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001473
Dan Egnor83861e72009-09-17 16:17:55 -07001474 // TODO - We call finishBackup() for each application backed up, because
1475 // we need to know now whether it succeeded or failed. Instead, we should
1476 // hold off on finishBackup() until the end, which implies holding off on
1477 // renaming *all* the output state files (see below) until that happens.
1478
Dan Egnor01445162009-09-21 17:04:05 -07001479 if (result == BackupConstants.TRANSPORT_OK) {
1480 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001481 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001482 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001483 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001484 }
1485
1486 // After successful transport, delete the now-stale data
1487 // and juggle the files so that next time we supply the agent
1488 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001489 if (result == BackupConstants.TRANSPORT_OK) {
1490 backupDataName.delete();
1491 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001493 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001494 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001495 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001496 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001497 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001498 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001499 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001500 } finally {
1501 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001502 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001503
Dan Egnor01445162009-09-21 17:04:05 -07001504 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001505 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001506 }
1507
Christopher Tatedf01dea2009-06-09 20:45:02 -07001508
1509 // ----- Restore handling -----
1510
Christopher Tate78dd4a72009-11-04 11:49:08 -08001511 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1512 // If the target resides on the system partition, we allow it to restore
1513 // data from the like-named package in a restore set even if the signatures
1514 // do not match. (Unlike general applications, those flashed to the system
1515 // partition will be signed with the device's platform certificate, so on
1516 // different phones the same system app will have different signatures.)
1517 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001518 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001519 return true;
1520 }
1521
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001522 // Allow unsigned apps, but not signed on one device and unsigned on the other
1523 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001524 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001526 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001527 if ((storedSigs == null || storedSigs.length == 0)
1528 && (deviceSigs == null || deviceSigs.length == 0)) {
1529 return true;
1530 }
1531 if (storedSigs == null || deviceSigs == null) {
1532 return false;
1533 }
1534
Christopher Tateabce4e82009-06-18 18:35:32 -07001535 // !!! TODO: this demands that every stored signature match one
1536 // that is present on device, and does not demand the converse.
1537 // Is this this right policy?
1538 int nStored = storedSigs.length;
1539 int nDevice = deviceSigs.length;
1540
1541 for (int i=0; i < nStored; i++) {
1542 boolean match = false;
1543 for (int j=0; j < nDevice; j++) {
1544 if (storedSigs[i].equals(deviceSigs[j])) {
1545 match = true;
1546 break;
1547 }
1548 }
1549 if (!match) {
1550 return false;
1551 }
1552 }
1553 return true;
1554 }
1555
Christopher Tate44a27902010-01-27 17:15:49 -08001556 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001557 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001558 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001559 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001560 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001561 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001562 private int mPmToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001563
Christopher Tate5cbbf562009-06-22 16:44:51 -07001564 class RestoreRequest {
1565 public PackageInfo app;
1566 public int storedAppVersion;
1567
1568 RestoreRequest(PackageInfo _app, int _version) {
1569 app = _app;
1570 storedAppVersion = _version;
1571 }
1572 }
1573
Christopher Tate44a27902010-01-27 17:15:49 -08001574 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate1bb69062010-02-19 17:02:12 -08001575 long restoreSetToken, PackageInfo targetPackage, int pmToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001576 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001577 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001578 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001579 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001580 mPmToken = pmToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001581
1582 try {
1583 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1584 } catch (RemoteException e) {
1585 // can't happen; the transport is local
1586 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001587 }
1588
Christopher Tatedf01dea2009-06-09 20:45:02 -07001589 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001590 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001591 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001592 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001593 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001594
Christopher Tateb49ceb32010-02-08 16:22:24 -08001595 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001596 int error = -1; // assume error
1597
Dan Egnorefe52642009-06-24 00:16:33 -07001598 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001599 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001600 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001601 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001602
Dan Egnorefe52642009-06-24 00:16:33 -07001603 // Get the list of all packages which have backup enabled.
1604 // (Include the Package Manager metadata pseudo-package first.)
1605 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1606 PackageInfo omPackage = new PackageInfo();
1607 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1608 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001609
Dan Egnorefe52642009-06-24 00:16:33 -07001610 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001611 if (mTargetPackage == null) {
1612 restorePackages.addAll(agentPackages);
1613 } else {
1614 // Just one package to attempt restore of
1615 restorePackages.add(mTargetPackage);
1616 }
Dan Egnorefe52642009-06-24 00:16:33 -07001617
Christopher Tate7d562ec2009-06-25 18:03:43 -07001618 // let the observer know that we're running
1619 if (mObserver != null) {
1620 try {
1621 // !!! TODO: get an actual count from the transport after
1622 // its startRestore() runs?
1623 mObserver.restoreStarting(restorePackages.size());
1624 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001625 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001626 mObserver = null;
1627 }
1628 }
1629
Dan Egnor01445162009-09-21 17:04:05 -07001630 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1631 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001632 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001634 return;
1635 }
1636
1637 String packageName = mTransport.nextRestorePackage();
1638 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001639 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001640 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001641 return;
1642 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001644 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001645 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001646 return;
1647 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001648 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001649 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001650 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001651 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001652 return;
1653 }
1654
1655 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001656 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001657 mPackageManager, agentPackages);
1658 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1659
Christopher Tate8c032472009-07-02 14:28:47 -07001660 // Verify that the backup set includes metadata. If not, we can't do
1661 // signature/version verification etc, so we simply do not proceed with
1662 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001663 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001664 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001665 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001666 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001667 return;
1668 }
1669
Christopher Tate7d562ec2009-06-25 18:03:43 -07001670 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001671 for (;;) {
1672 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001673
Dan Egnorefe52642009-06-24 00:16:33 -07001674 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001676 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001677 return;
1678 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001679 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001680 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001681 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001682
Christopher Tate7d562ec2009-06-25 18:03:43 -07001683 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001684 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001685 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001686 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001687 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001688 mObserver = null;
1689 }
1690 }
1691
Dan Egnorefe52642009-06-24 00:16:33 -07001692 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1693 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001694 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001695 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001696 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001697 continue;
1698 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001699
Dan Egnorbb9001c2009-07-27 12:20:13 -07001700 PackageInfo packageInfo;
1701 try {
1702 int flags = PackageManager.GET_SIGNATURES;
1703 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1704 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001706 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001707 "Package missing on device");
1708 continue;
1709 }
1710
Dan Egnorefe52642009-06-24 00:16:33 -07001711 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001712 // Data is from a "newer" version of the app than we have currently
1713 // installed. If the app has not declared that it is prepared to
1714 // handle this case, we do not attempt the restore.
1715 if ((packageInfo.applicationInfo.flags
1716 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1717 String message = "Version " + metaInfo.versionCode
1718 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001719 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001720 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1721 packageName, message);
1722 continue;
1723 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001724 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001725 + " > installed " + packageInfo.versionCode
1726 + " but restoreAnyVersion");
1727 }
Dan Egnorefe52642009-06-24 00:16:33 -07001728 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001729
Christopher Tate78dd4a72009-11-04 11:49:08 -08001730 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001731 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001732 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001733 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001734 continue;
1735 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001736
Joe Onorato8a9b2202010-02-26 18:56:32 -08001737 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001738 + " restore version [" + metaInfo.versionCode
1739 + "] is compatible with installed version ["
1740 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001741
Christopher Tate3de55bc2010-03-12 17:28:08 -08001742 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001743 IBackupAgent agent = bindToAgentSynchronous(
1744 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001745 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001746 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001747 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001748 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001749 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001750 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001751 }
1752
Christopher Tate5e1ab332009-09-01 20:32:49 -07001753 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001754 try {
1755 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001756 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001757 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001758 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001759 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001760
1761 // The agent was probably running with a stub Application object,
1762 // which isn't a valid run mode for the main app logic. Shut
1763 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001764 // usual full initialization. Note that this is only done for
1765 // full-system restores: when a single app has requested a restore,
1766 // it is explicitly not killed following that operation.
1767 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001768 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001769 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001770 + packageInfo.applicationInfo.processName);
1771 mActivityManager.killApplicationProcess(
1772 packageInfo.applicationInfo.processName,
1773 packageInfo.applicationInfo.uid);
1774 }
Dan Egnorefe52642009-06-24 00:16:33 -07001775 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001776 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001777
1778 // if we get this far, report success to the observer
1779 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001780 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001781 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001782 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001784 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001786
Dan Egnorefe52642009-06-24 00:16:33 -07001787 try {
1788 mTransport.finishRestore();
1789 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001790 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001791 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001792
1793 if (mObserver != null) {
1794 try {
1795 mObserver.restoreFinished(error);
1796 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001798 }
1799 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001800
Christopher Tate84725812010-02-04 15:52:40 -08001801 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001802 // ancestral dataset, as well as the set of apps that are possibly
1803 // restoreable from the dataset
1804 if (mTargetPackage == null && pmAgent != null) {
1805 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001806 mAncestralToken = mToken;
1807 writeRestoreTokens();
1808 }
1809
Christopher Tate1bb69062010-02-19 17:02:12 -08001810 // We must under all circumstances tell the Package Manager to
1811 // proceed with install notifications if it's waiting for us.
1812 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001813 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001814 try {
1815 mPackageManagerBinder.finishPackageInstall(mPmToken);
1816 } catch (RemoteException e) { /* can't happen */ }
1817 }
1818
Christopher Tateb6787f22009-07-02 17:40:45 -07001819 // done; we can finally release the wakelock
1820 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001821 }
1822 }
1823
Dan Egnorefe52642009-06-24 00:16:33 -07001824 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1825 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001826 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001827 final String packageName = app.packageName;
1828
Joe Onorato8a9b2202010-02-26 18:56:32 -08001829 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001830
Christopher Tatec7b31e32009-06-10 15:49:30 -07001831 // !!! TODO: get the dirs from the transport
1832 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833 File newStateName = new File(mStateDir, packageName + ".new");
1834 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001835
Dan Egnorbb9001c2009-07-27 12:20:13 -07001836 ParcelFileDescriptor backupData = null;
1837 ParcelFileDescriptor newState = null;
1838
Christopher Tate44a27902010-01-27 17:15:49 -08001839 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001840 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001841 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001842 backupData = ParcelFileDescriptor.open(backupDataName,
1843 ParcelFileDescriptor.MODE_READ_WRITE |
1844 ParcelFileDescriptor.MODE_CREATE |
1845 ParcelFileDescriptor.MODE_TRUNCATE);
1846
Dan Egnor01445162009-09-21 17:04:05 -07001847 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001848 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001849 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001850 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001851 }
1852
1853 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001854 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001855 backupData = ParcelFileDescriptor.open(backupDataName,
1856 ParcelFileDescriptor.MODE_READ_ONLY);
1857
Dan Egnorbb9001c2009-07-27 12:20:13 -07001858 newState = ParcelFileDescriptor.open(newStateName,
1859 ParcelFileDescriptor.MODE_READ_WRITE |
1860 ParcelFileDescriptor.MODE_CREATE |
1861 ParcelFileDescriptor.MODE_TRUNCATE);
1862
Christopher Tate44a27902010-01-27 17:15:49 -08001863 // Kick off the restore, checking for hung agents
1864 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1865 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1866 boolean success = waitUntilOperationComplete(token);
1867
1868 if (!success) {
1869 throw new RuntimeException("restore timeout");
1870 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001871
1872 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001873 //
1874 // !!! TODO: the restored data should be migrated on the server
1875 // side into the current dataset. In that case the new state file
1876 // we just created would reflect the data already extant in the
1877 // backend, so there'd be nothing more to do. Until that happens,
1878 // however, we need to make sure that we record the data to the
1879 // current backend dataset. (Yes, this means shipping the data over
1880 // the wire in both directions. That's bad, but consistency comes
1881 // first, then efficiency.) Once we introduce server-side data
1882 // migration to the newly-restored device's dataset, we will change
1883 // the following from a discard of the newly-written state to the
1884 // "correct" operation of renaming into the canonical state blob.
1885 newStateName.delete(); // TODO: remove; see above comment
1886 //newStateName.renameTo(savedStateName); // TODO: replace with this
1887
Dan Egnorbb9001c2009-07-27 12:20:13 -07001888 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001890 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001892 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001893
Christopher Tate96733042009-07-20 14:49:13 -07001894 // If the agent fails restore, it might have put the app's data
1895 // into an incoherent state. For consistency we wipe its data
1896 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001897 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001898 } finally {
1899 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001900 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1901 try { if (newState != null) newState.close(); } catch (IOException e) {}
1902 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001903 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001904 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001905 }
1906 }
1907
Christopher Tate44a27902010-01-27 17:15:49 -08001908 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001909 IBackupTransport mTransport;
1910 PackageInfo mPackage;
1911
Christopher Tate44a27902010-01-27 17:15:49 -08001912 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001913 mTransport = transport;
1914 mPackage = packageInfo;
1915 }
1916
Christopher Tateee0e78a2009-07-02 11:17:03 -07001917 public void run() {
1918 try {
1919 // Clear the on-device backup state to ensure a full backup next time
1920 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1921 File stateFile = new File(stateDir, mPackage.packageName);
1922 stateFile.delete();
1923
1924 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001925 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001926 mTransport.clearBackupData(mPackage);
1927 } catch (RemoteException e) {
1928 // can't happen; the transport is local
1929 } finally {
1930 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001931 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001932 mTransport.finishBackup();
1933 } catch (RemoteException e) {
1934 // can't happen; the transport is local
1935 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001936
1937 // Last but not least, release the cpu
1938 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001939 }
1940 }
1941 }
1942
Christopher Tate44a27902010-01-27 17:15:49 -08001943 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001944 HashSet<String> mQueue;
1945
Christopher Tate44a27902010-01-27 17:15:49 -08001946 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001947 mQueue = transportNames;
1948 }
1949
Christopher Tate4cc86e12009-09-21 19:36:51 -07001950 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001951 try {
1952 for (String transportName : mQueue) {
1953 IBackupTransport transport = getTransport(transportName);
1954 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001955 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001956 continue;
1957 }
1958
Joe Onorato8a9b2202010-02-26 18:56:32 -08001959 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001960 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001961 long startRealtime = SystemClock.elapsedRealtime();
1962 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001963
Christopher Tate4cc86e12009-09-21 19:36:51 -07001964 if (status == BackupConstants.TRANSPORT_OK) {
1965 status = transport.finishBackup();
1966 }
1967
1968 // Okay, the wipe really happened. Clean up our local bookkeeping.
1969 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001970 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001971 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001972 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001973 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001974 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001975 synchronized (mQueueLock) {
1976 recordInitPendingLocked(false, transportName);
1977 }
Dan Egnor726247c2009-09-29 19:12:31 -07001978 } else {
1979 // If this didn't work, requeue this one and try again
1980 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08001981 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001982 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001983 synchronized (mQueueLock) {
1984 recordInitPendingLocked(true, transportName);
1985 }
1986 // do this via another alarm to make sure of the wakelock states
1987 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001988 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07001989 + transportName + " resched in " + delay);
1990 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1991 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001992 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001993 }
1994 } catch (RemoteException e) {
1995 // can't happen; the transports are local
1996 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001997 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001998 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001999 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002000 mWakelock.release();
2001 }
2002 }
2003 }
2004
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002005 private void dataChangedImpl(String packageName) {
2006 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2007 dataChangedImpl(packageName, targets);
2008 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002009
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002010 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002011 // Record that we need a backup pass for the caller. Since multiple callers
2012 // may share a uid, we need to note all candidates within that uid and schedule
2013 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002014 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002015
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002016 if (targets == null) {
2017 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2018 + " uid=" + Binder.getCallingUid());
2019 return;
2020 }
2021
2022 synchronized (mQueueLock) {
2023 // Note that this client has made data changes that need to be backed up
2024 for (ApplicationInfo app : targets) {
2025 // validate the caller-supplied package name against the known set of
2026 // packages associated with this uid
2027 if (app.packageName.equals(packageName)) {
2028 // Add the caller to the set of pending backups. If there is
2029 // one already there, then overwrite it, but no harm done.
2030 BackupRequest req = new BackupRequest(app, false);
2031 if (mPendingBackups.put(app, req) == null) {
2032 // Journal this request in case of crash. The put()
2033 // operation returned null when this package was not already
2034 // in the set; we want to avoid touching the disk redundantly.
2035 writeToJournalLocked(packageName);
2036
2037 if (DEBUG) {
2038 int numKeys = mPendingBackups.size();
2039 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2040 for (BackupRequest b : mPendingBackups.values()) {
2041 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2042 }
2043 }
2044 }
2045 }
2046 }
2047 }
2048 }
2049
2050 // Note: packageName is currently unused, but may be in the future
2051 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002052 // If the caller does not hold the BACKUP permission, it can only request a
2053 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002054 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002055 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002056 synchronized (mBackupParticipants) {
2057 return mBackupParticipants.get(Binder.getCallingUid());
2058 }
2059 }
2060
2061 // a caller with full permission can ask to back up any participating app
2062 // !!! TODO: allow backup of ANY app?
2063 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2064 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002065 int N = mBackupParticipants.size();
2066 for (int i = 0; i < N; i++) {
2067 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2068 if (s != null) {
2069 targets.addAll(s);
2070 }
2071 }
2072 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002073 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002074 }
Christopher Tate46758122009-05-06 11:22:00 -07002075
Christopher Tatecde87f42009-06-12 12:55:53 -07002076 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002077 RandomAccessFile out = null;
2078 try {
2079 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2080 out = new RandomAccessFile(mJournal, "rws");
2081 out.seek(out.length());
2082 out.writeUTF(str);
2083 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002084 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002085 mJournal = null;
2086 } finally {
2087 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002088 }
2089 }
2090
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002091 // ----- IBackupManager binder interface -----
2092
2093 public void dataChanged(final String packageName) {
2094 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2095 if (targets == null) {
2096 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2097 + " uid=" + Binder.getCallingUid());
2098 return;
2099 }
2100
2101 mBackupHandler.post(new Runnable() {
2102 public void run() {
2103 dataChangedImpl(packageName, targets);
2104 }
2105 });
2106 }
2107
Christopher Tateee0e78a2009-07-02 11:17:03 -07002108 // Clear the given package's backup data from the current transport
2109 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002110 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002111 PackageInfo info;
2112 try {
2113 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2114 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002115 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002116 return;
2117 }
2118
2119 // If the caller does not hold the BACKUP permission, it can only request a
2120 // wipe of its own backed-up data.
2121 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002122 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002123 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2124 apps = mBackupParticipants.get(Binder.getCallingUid());
2125 } else {
2126 // a caller with full permission can ask to back up any participating app
2127 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002128 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002129 apps = new HashSet<ApplicationInfo>();
2130 int N = mBackupParticipants.size();
2131 for (int i = 0; i < N; i++) {
2132 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2133 if (s != null) {
2134 apps.addAll(s);
2135 }
2136 }
2137 }
2138
2139 // now find the given package in the set of candidate apps
2140 for (ApplicationInfo app : apps) {
2141 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002142 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002143 // found it; fire off the clear request
2144 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002145 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002146 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002147 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2148 new ClearParams(getTransport(mCurrentTransport), info));
2149 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002150 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002151 }
2152 break;
2153 }
2154 }
2155 }
2156
Christopher Tateace7f092009-06-15 18:07:25 -07002157 // Run a backup pass immediately for any applications that have declared
2158 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002159 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002160 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002161
Joe Onorato8a9b2202010-02-26 18:56:32 -08002162 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002163 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002164 // Because the alarms we are using can jitter, and we want an *immediate*
2165 // backup pass to happen, we restart the timer beginning with "next time,"
2166 // then manually fire the backup trigger intent ourselves.
2167 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002168 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002169 mRunBackupIntent.send();
2170 } catch (PendingIntent.CanceledException e) {
2171 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002172 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002173 }
Christopher Tate46758122009-05-06 11:22:00 -07002174 }
2175 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002176
Christopher Tate8031a3d2009-07-06 16:36:05 -07002177 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002178 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2180 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002181
Joe Onorato8a9b2202010-02-26 18:56:32 -08002182 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002183
Christopher Tate6ef58a12009-06-29 14:56:28 -07002184 boolean wasEnabled = mEnabled;
2185 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002186 Settings.Secure.putInt(mContext.getContentResolver(),
2187 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002188 mEnabled = enable;
2189 }
2190
Christopher Tate49401dd2009-07-01 12:34:29 -07002191 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002192 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002193 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002194 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002195 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002196 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002197 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002198
Christopher Tateb6787f22009-07-02 17:40:45 -07002199 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002200
2201 // This also constitutes an opt-out, so we wipe any data for
2202 // this device from the backend. We start that process with
2203 // an alarm in order to guarantee wakelock states.
2204 if (wasEnabled && mProvisioned) {
2205 // NOTE: we currently flush every registered transport, not just
2206 // the currently-active one.
2207 HashSet<String> allTransports;
2208 synchronized (mTransports) {
2209 allTransports = new HashSet<String>(mTransports.keySet());
2210 }
2211 // build the set of transports for which we are posting an init
2212 for (String transport : allTransports) {
2213 recordInitPendingLocked(true, transport);
2214 }
2215 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2216 mRunInitIntent);
2217 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002218 }
2219 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002220 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002221
Christopher Tatecce9da52010-02-03 15:11:15 -08002222 // Enable/disable automatic restore of app data at install time
2223 public void setAutoRestore(boolean doAutoRestore) {
2224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2225 "setBackupEnabled");
2226
Joe Onorato8a9b2202010-02-26 18:56:32 -08002227 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002228
2229 synchronized (this) {
2230 Settings.Secure.putInt(mContext.getContentResolver(),
2231 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2232 mAutoRestore = doAutoRestore;
2233 }
2234 }
2235
Christopher Tate8031a3d2009-07-06 16:36:05 -07002236 // Mark the backup service as having been provisioned
2237 public void setBackupProvisioned(boolean available) {
2238 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2239 "setBackupProvisioned");
2240
2241 boolean wasProvisioned = mProvisioned;
2242 synchronized (this) {
2243 Settings.Secure.putInt(mContext.getContentResolver(),
2244 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2245 mProvisioned = available;
2246 }
2247
2248 synchronized (mQueueLock) {
2249 if (available && !wasProvisioned && mEnabled) {
2250 // we're now good to go, so start the backup alarms
2251 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2252 } else if (!available) {
2253 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002254 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002255 mAlarmManager.cancel(mRunBackupIntent);
2256 }
2257 }
2258 }
2259
2260 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002261 // We used to use setInexactRepeating(), but that may be linked to
2262 // backups running at :00 more often than not, creating load spikes.
2263 // Schedule at an exact time for now, and also add a bit of "fuzz".
2264
2265 Random random = new Random();
2266 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2267 random.nextInt(FUZZ_MILLIS);
2268 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2269 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002270 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002271 }
2272
Christopher Tate6ef58a12009-06-29 14:56:28 -07002273 // Report whether the backup mechanism is currently enabled
2274 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002275 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002276 return mEnabled; // no need to synchronize just to read it
2277 }
2278
Christopher Tate91717492009-06-26 21:07:13 -07002279 // Report the name of the currently active transport
2280 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002282 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002283 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002284 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002285 }
2286
Christopher Tate91717492009-06-26 21:07:13 -07002287 // Report all known, available backup transports
2288 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002290
Christopher Tate91717492009-06-26 21:07:13 -07002291 String[] list = null;
2292 ArrayList<String> known = new ArrayList<String>();
2293 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2294 if (entry.getValue() != null) {
2295 known.add(entry.getKey());
2296 }
2297 }
2298
2299 if (known.size() > 0) {
2300 list = new String[known.size()];
2301 known.toArray(list);
2302 }
2303 return list;
2304 }
2305
2306 // Select which transport to use for the next backup operation. If the given
2307 // name is not one of the available transports, no action is taken and the method
2308 // returns null.
2309 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002311
2312 synchronized (mTransports) {
2313 String prevTransport = null;
2314 if (mTransports.get(transport) != null) {
2315 prevTransport = mCurrentTransport;
2316 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002317 Settings.Secure.putString(mContext.getContentResolver(),
2318 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002319 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002320 + " returning " + prevTransport);
2321 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002322 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002323 }
2324 return prevTransport;
2325 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002326 }
2327
2328 // Callback: a requested backup agent has been instantiated. This should only
2329 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002330 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002331 synchronized(mAgentConnectLock) {
2332 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002333 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002334 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2335 mConnectedAgent = agent;
2336 mConnecting = false;
2337 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002338 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002339 + " claiming agent connected");
2340 }
2341 mAgentConnectLock.notifyAll();
2342 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002343 }
2344
2345 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2346 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002347 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002348 public void agentDisconnected(String packageName) {
2349 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002350 synchronized(mAgentConnectLock) {
2351 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2352 mConnectedAgent = null;
2353 mConnecting = false;
2354 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002355 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002356 + " claiming agent disconnected");
2357 }
2358 mAgentConnectLock.notifyAll();
2359 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002360 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002361
Christopher Tate1bb69062010-02-19 17:02:12 -08002362 // An application being installed will need a restore pass, then the Package Manager
2363 // will need to be told when the restore is finished.
2364 public void restoreAtInstall(String packageName, int token) {
2365 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002366 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002367 + " attemping install-time restore");
2368 return;
2369 }
2370
2371 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002372 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002373 + " token=" + Integer.toHexString(token));
2374
Christopher Tatef0872722010-02-25 15:22:48 -08002375 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002376 // okay, we're going to attempt a restore of this package from this restore set.
2377 // The eventual message back into the Package Manager to run the post-install
2378 // steps for 'token' will be issued from the restore handling code.
2379
2380 // We can use a synthetic PackageInfo here because:
2381 // 1. We know it's valid, since the Package Manager supplied the name
2382 // 2. Only the packageName field will be used by the restore code
2383 PackageInfo pkg = new PackageInfo();
2384 pkg.packageName = packageName;
2385
2386 mWakelock.acquire();
2387 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2388 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2389 restoreSet, pkg, token);
2390 mBackupHandler.sendMessage(msg);
2391 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002392 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2393 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002394 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002395 try {
2396 mPackageManagerBinder.finishPackageInstall(token);
2397 } catch (RemoteException e) { /* can't happen */ }
2398 }
2399 }
2400
Christopher Tate8c850b72009-06-07 19:33:20 -07002401 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002402 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002403 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002404
2405 synchronized(this) {
2406 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002407 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002408 return null;
2409 }
Christopher Tate80202c82010-01-25 19:37:47 -08002410 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002411 }
2412 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002413 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002414
Christopher Tate44a27902010-01-27 17:15:49 -08002415 // Note that a currently-active backup agent has notified us that it has
2416 // completed the given outstanding asynchronous backup/restore operation.
2417 public void opComplete(int token) {
2418 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002419 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002420 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2421 mCurrentOpLock.notifyAll();
2422 }
2423 }
2424
Christopher Tate9b3905c2009-06-08 15:24:01 -07002425 // ----- Restore session -----
2426
Christopher Tate80202c82010-01-25 19:37:47 -08002427 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002428 private static final String TAG = "RestoreSession";
2429
Christopher Tate9b3905c2009-06-08 15:24:01 -07002430 private IBackupTransport mRestoreTransport = null;
2431 RestoreSet[] mRestoreSets = null;
2432
Christopher Tate80202c82010-01-25 19:37:47 -08002433 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002434 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002435 }
2436
2437 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002438 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002439 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002440 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002441 if (observer == null) {
2442 throw new IllegalArgumentException("Observer must not be null");
2443 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002444
Christopher Tate1bb69062010-02-19 17:02:12 -08002445 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002446 try {
Christopher Tate43383042009-07-13 15:17:13 -07002447 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002448 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002449 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002450 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002451 // spin off the transport request to our service thread
2452 mWakelock.acquire();
2453 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2454 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2455 mBackupHandler.sendMessage(msg);
2456 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002457 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002458 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002459 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002460 } finally {
2461 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002462 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002463 }
2464
Christopher Tate84725812010-02-04 15:52:40 -08002465 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002466 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2467 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002468
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 if (DEBUG) Slog.d(TAG, "performRestore token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002470 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002471
Dan Egnor0084da52009-07-29 12:57:16 -07002472 if (mRestoreTransport == null || mRestoreSets == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002473 Slog.e(TAG, "Ignoring performRestore() with no restore set");
Dan Egnor0084da52009-07-29 12:57:16 -07002474 return -1;
2475 }
2476
Christopher Tate21ab6a52009-09-24 18:01:46 -07002477 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002478 for (int i = 0; i < mRestoreSets.length; i++) {
2479 if (token == mRestoreSets[i].token) {
2480 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002481 mWakelock.acquire();
2482 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2483 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2484 mBackupHandler.sendMessage(msg);
2485 Binder.restoreCallingIdentity(oldId);
2486 return 0;
2487 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002488 }
2489 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002490
Joe Onorato8a9b2202010-02-26 18:56:32 -08002491 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002492 return -1;
2493 }
2494
Christopher Tate84725812010-02-04 15:52:40 -08002495 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002496 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002497
2498 PackageInfo app = null;
2499 try {
2500 app = mPackageManager.getPackageInfo(packageName, 0);
2501 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002502 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002503 return -1;
2504 }
2505
2506 // If the caller is not privileged and is not coming from the target
2507 // app's uid, throw a permission exception back to the caller.
2508 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2509 Binder.getCallingPid(), Binder.getCallingUid());
2510 if ((perm == PackageManager.PERMISSION_DENIED) &&
2511 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002512 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002513 + " or calling uid=" + Binder.getCallingUid());
2514 throw new SecurityException("No permission to restore other packages");
2515 }
2516
Christopher Tate7d411a32010-02-26 11:27:08 -08002517 // If the package has no backup agent, we obviously cannot proceed
2518 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002519 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002520 return -1;
2521 }
2522
Christopher Tate84725812010-02-04 15:52:40 -08002523 // So far so good; we're allowed to try to restore this package. Now
2524 // check whether there is data for it in the current dataset, falling back
2525 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002526 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002527
2528 // If we didn't come up with a place to look -- no ancestral dataset and
2529 // the app has never been backed up from this device -- there's nothing
2530 // to do but return failure.
2531 if (token == 0) {
2532 return -1;
2533 }
2534
2535 // Ready to go: enqueue the restore request and claim success
2536 long oldId = Binder.clearCallingIdentity();
2537 mWakelock.acquire();
2538 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002539 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002540 mBackupHandler.sendMessage(msg);
2541 Binder.restoreCallingIdentity(oldId);
2542 return 0;
2543 }
2544
Dan Egnor0084da52009-07-29 12:57:16 -07002545 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002547 "endRestoreSession");
2548
Joe Onorato8a9b2202010-02-26 18:56:32 -08002549 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002550
Dan Egnor0084da52009-07-29 12:57:16 -07002551 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002552 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002553 try {
2554 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2555 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002556 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002557 } finally {
2558 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002559 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002560 }
2561 }
2562
2563 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002564 if (BackupManagerService.this.mActiveRestoreSession == this) {
2565 BackupManagerService.this.mActiveRestoreSession = null;
2566 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002567 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002568 }
2569 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002570 }
2571 }
2572
Christopher Tate043dadc2009-06-02 16:11:00 -07002573
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002574 @Override
2575 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2576 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002577 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002578 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002579 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002580 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002581 pw.println("Last backup pass: " + mLastBackupPass
2582 + " (now = " + System.currentTimeMillis() + ')');
2583 pw.println(" next scheduled: " + mNextBackupPass);
2584
Christopher Tate91717492009-06-26 21:07:13 -07002585 pw.println("Available transports:");
2586 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002587 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2588 try {
2589 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2590 for (File f : dir.listFiles()) {
2591 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2592 }
2593 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002594 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002595 pw.println(" Error: " + e);
2596 }
Christopher Tate91717492009-06-26 21:07:13 -07002597 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002598
2599 pw.println("Pending init: " + mPendingInits.size());
2600 for (String s : mPendingInits) {
2601 pw.println(" " + s);
2602 }
2603
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002604 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002605 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002606 for (int i=0; i<N; i++) {
2607 int uid = mBackupParticipants.keyAt(i);
2608 pw.print(" uid: ");
2609 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002610 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2611 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002612 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002613 }
2614 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002615
Christopher Tateb49ceb32010-02-08 16:22:24 -08002616 pw.println("Ancestral packages: "
2617 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002618 if (mAncestralPackages != null) {
2619 for (String pkg : mAncestralPackages) {
2620 pw.println(" " + pkg);
2621 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002622 }
2623
Christopher Tate73e02522009-07-15 14:18:26 -07002624 pw.println("Ever backed up: " + mEverStoredApps.size());
2625 for (String pkg : mEverStoredApps) {
2626 pw.println(" " + pkg);
2627 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002628
2629 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002630 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002631 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002632 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002633 }
2634 }
Christopher Tate487529a2009-04-29 14:03:25 -07002635}