blob: aa87f29314800e5518ed3ae53c8c1efc98a40e8a [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";
Christopher Tate13f4a642009-09-30 20:06:45 -070087 private static final boolean DEBUG = false;
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 }
Christopher Tate1168baa2010-02-17 13:03:40 -0800588 } catch (FileNotFoundException fnf) {
589 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800590 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800591 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800592 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800593 }
594
Christopher Tatee97e8072009-07-15 16:45:50 -0700595 // Keep a log of what apps we've ever backed up. Because we might have
596 // rebooted in the middle of an operation that was removing something from
597 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700598 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700599 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700600
Christopher Tatee97e8072009-07-15 16:45:50 -0700601 // If we were in the middle of removing something from the ever-backed-up
602 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700603 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700604 if (tempProcessedFile.exists()) {
605 tempProcessedFile.delete();
606 }
607
Dan Egnor852f8e42009-09-30 11:20:45 -0700608 // If there are previous contents, parse them out then start a new
609 // file to continue the recordkeeping.
610 if (mEverStored.exists()) {
611 RandomAccessFile temp = null;
612 RandomAccessFile in = null;
613
614 try {
615 temp = new RandomAccessFile(tempProcessedFile, "rws");
616 in = new RandomAccessFile(mEverStored, "r");
617
618 while (true) {
619 PackageInfo info;
620 String pkg = in.readUTF();
621 try {
622 info = mPackageManager.getPackageInfo(pkg, 0);
623 mEverStoredApps.add(pkg);
624 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800625 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700626 } catch (NameNotFoundException e) {
627 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800628 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700629 }
630 }
631 } catch (EOFException e) {
632 // Once we've rewritten the backup history log, atomically replace the
633 // old one with the new one then reopen the file for continuing use.
634 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800635 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700636 }
637 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800638 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700639 } finally {
640 try { if (temp != null) temp.close(); } catch (IOException e) {}
641 try { if (in != null) in.close(); } catch (IOException e) {}
642 }
643 }
644
Christopher Tate73e02522009-07-15 14:18:26 -0700645 // Register for broadcasts about package install, etc., so we can
646 // update the provider list.
647 IntentFilter filter = new IntentFilter();
648 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
649 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
650 filter.addDataScheme("package");
651 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800652 // Register for events related to sdcard installation.
653 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800654 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
655 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800656 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700657 }
658
Christopher Tatecde87f42009-06-12 12:55:53 -0700659 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700660 for (File f : mJournalDir.listFiles()) {
661 if (mJournal == null || f.compareTo(mJournal) != 0) {
662 // This isn't the current journal, so it must be a leftover. Read
663 // out the package names mentioned there and schedule them for
664 // backup.
665 RandomAccessFile in = null;
666 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800667 Slog.i(TAG, "Found stale backup journal, scheduling:");
Dan Egnor852f8e42009-09-30 11:20:45 -0700668 in = new RandomAccessFile(f, "r");
669 while (true) {
670 String packageName = in.readUTF();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800671 Slog.i(TAG, " + " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700672 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700673 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700674 } catch (EOFException e) {
675 // no more data; we're done
676 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800677 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700678 } finally {
679 // close/delete the file
680 try { if (in != null) in.close(); } catch (IOException e) {}
681 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700682 }
683 }
684 }
685 }
686
Christopher Tate4cc86e12009-09-21 19:36:51 -0700687 // Maintain persistent state around whether need to do an initialize operation.
688 // Must be called with the queue lock held.
689 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800690 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700691 + " on transport " + transportName);
692 try {
693 IBackupTransport transport = getTransport(transportName);
694 String transportDirName = transport.transportDirName();
695 File stateDir = new File(mBaseStateDir, transportDirName);
696 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
697
698 if (isPending) {
699 // We need an init before we can proceed with sending backup data.
700 // Record that with an entry in our set of pending inits, as well as
701 // journaling it via creation of a sentinel file.
702 mPendingInits.add(transportName);
703 try {
704 (new FileOutputStream(initPendingFile)).close();
705 } catch (IOException ioe) {
706 // Something is badly wrong with our permissions; just try to move on
707 }
708 } else {
709 // No more initialization needed; wipe the journal and reset our state.
710 initPendingFile.delete();
711 mPendingInits.remove(transportName);
712 }
713 } catch (RemoteException e) {
714 // can't happen; the transport is local
715 }
716 }
717
Christopher Tated55e18a2009-09-21 10:12:59 -0700718 // Reset all of our bookkeeping, in response to having been told that
719 // the backend data has been wiped [due to idle expiry, for example],
720 // so we must re-upload all saved settings.
721 void resetBackupState(File stateFileDir) {
722 synchronized (mQueueLock) {
723 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700724 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700725 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700726
Christopher Tate84725812010-02-04 15:52:40 -0800727 mCurrentToken = 0;
728 writeRestoreTokens();
729
Christopher Tated55e18a2009-09-21 10:12:59 -0700730 // Remove all the state files
731 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700732 // ... but don't touch the needs-init sentinel
733 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
734 sf.delete();
735 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700736 }
737
738 // Enqueue a new backup of every participant
739 int N = mBackupParticipants.size();
740 for (int i=0; i<N; i++) {
741 int uid = mBackupParticipants.keyAt(i);
742 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
743 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700744 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700745 }
746 }
747 }
748 }
749
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800750 // Add a transport to our set of available backends. If 'transport' is null, this
751 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700752 private void registerTransport(String name, IBackupTransport transport) {
753 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800754 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800755 if (transport != null) {
756 mTransports.put(name, transport);
757 } else {
758 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800759 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800760 mCurrentTransport = null;
761 }
762 // Nothing further to do in the unregistration case
763 return;
764 }
Christopher Tate91717492009-06-26 21:07:13 -0700765 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700766
767 // If the init sentinel file exists, we need to be sure to perform the init
768 // as soon as practical. We also create the state directory at registration
769 // time to ensure it's present from the outset.
770 try {
771 String transportName = transport.transportDirName();
772 File stateDir = new File(mBaseStateDir, transportName);
773 stateDir.mkdirs();
774
775 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
776 if (initSentinel.exists()) {
777 synchronized (mQueueLock) {
778 mPendingInits.add(transportName);
779
780 // TODO: pick a better starting time than now + 1 minute
781 long delay = 1000 * 60; // one minute, in milliseconds
782 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
783 System.currentTimeMillis() + delay, mRunInitIntent);
784 }
785 }
786 } catch (RemoteException e) {
787 // can't happen, the transport is local
788 }
Christopher Tate91717492009-06-26 21:07:13 -0700789 }
790
Christopher Tate3799bc22009-05-06 16:13:56 -0700791 // ----- Track installation/removal of packages -----
792 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
793 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800794 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700795
Christopher Tate3799bc22009-05-06 16:13:56 -0700796 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800797 boolean replacing = false;
798 boolean added = false;
799 Bundle extras = intent.getExtras();
800 String pkgList[] = null;
801 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
802 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
803 Uri uri = intent.getData();
804 if (uri == null) {
805 return;
806 }
807 String pkgName = uri.getSchemeSpecificPart();
808 if (pkgName != null) {
809 pkgList = new String[] { pkgName };
810 }
811 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
812 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800813 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800814 added = true;
815 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800816 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800817 added = false;
818 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
819 }
820 if (pkgList == null || pkgList.length == 0) {
821 return;
822 }
823 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700824 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800825 for (String pkgName : pkgList) {
826 if (replacing) {
827 // The package was just upgraded
828 updatePackageParticipantsLocked(pkgName);
829 } else {
830 // The package was just added
831 addPackageParticipantsLocked(pkgName);
832 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700833 }
834 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800835 } else {
836 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700837 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
838 } else {
839 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800840 for (String pkgName : pkgList) {
841 removePackageParticipantsLocked(pkgName);
842 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700843 }
844 }
845 }
846 }
847 };
848
Dan Egnor87a02bc2009-06-17 02:30:10 -0700849 // ----- Track connection to GoogleBackupTransport service -----
850 ServiceConnection mGoogleConnection = new ServiceConnection() {
851 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700853 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700854 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700855 }
856
857 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800858 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700859 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700860 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700861 }
862 };
863
Christopher Tate181fafa2009-05-14 11:12:14 -0700864 // Add the backup agents in the given package to our set of known backup participants.
865 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700866 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700867 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800868 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700869 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700870 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700871 }
872
Christopher Tate181fafa2009-05-14 11:12:14 -0700873 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700874 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700875 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700877 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800878 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700879 + " uid=" + p.applicationInfo.uid
880 + " killAfterRestore="
881 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700882 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700883 }
884 }
885
Dan Egnorefe52642009-06-24 00:16:33 -0700886 for (PackageInfo pkg : targetPkgs) {
887 if (packageName == null || pkg.packageName.equals(packageName)) {
888 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700889 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700890 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700891 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700892 mBackupParticipants.put(uid, set);
893 }
Dan Egnorefe52642009-06-24 00:16:33 -0700894 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700895
896 // If we've never seen this app before, schedule a backup for it
897 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800898 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700899 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700900 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700901 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700902 }
Christopher Tate487529a2009-04-29 14:03:25 -0700903 }
904 }
905
Christopher Tate6785dd82009-06-18 15:58:25 -0700906 // Remove the given package's entry from our known active set. If
907 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700908 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800909 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700910 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700911 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700912 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700913 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700914 int flags = PackageManager.GET_SIGNATURES;
915 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700916 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700917 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700918 }
919 } else {
920 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700921 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700922 }
923 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700924 }
925
Joe Onorato8ad02812009-05-13 01:41:44 -0400926 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700927 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700928 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800929 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700930 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700931 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800932 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700933 }
934 }
Dan Egnorefe52642009-06-24 00:16:33 -0700935 for (PackageInfo pkg : agents) {
936 if (packageName == null || pkg.packageName.equals(packageName)) {
937 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700938 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700939 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700940 // Find the existing entry with the same package name, and remove it.
941 // We can't just remove(app) because the instances are different.
942 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700943 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700944 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700945 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700946 break;
947 }
948 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700949 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700950 mBackupParticipants.delete(uid);
951 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700952 }
953 }
954 }
955 }
956
Christopher Tate181fafa2009-05-14 11:12:14 -0700957 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700958 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700959 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700960 int flags = PackageManager.GET_SIGNATURES;
961 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
962 int N = packages.size();
963 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700964 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700965 try {
966 ApplicationInfo app = pkg.applicationInfo;
967 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800968 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700969 packages.remove(a);
970 }
971 else {
972 // we will need the shared library path, so look that up and store it here
973 app = mPackageManager.getApplicationInfo(pkg.packageName,
974 PackageManager.GET_SHARED_LIBRARY_FILES);
975 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
976 }
977 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700978 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700979 }
980 }
Dan Egnorefe52642009-06-24 00:16:33 -0700981 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700982 }
Christopher Tateaa088442009-06-16 18:25:46 -0700983
Christopher Tate3799bc22009-05-06 16:13:56 -0700984 // Reset the given package's known backup participants. Unlike add/remove, the update
985 // action cannot be passed a null package name.
986 void updatePackageParticipantsLocked(String packageName) {
987 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800988 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700989 return;
990 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700992
993 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700994 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700995 removePackageParticipantsLockedInner(packageName, allApps);
996 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700997 }
998
Christopher Tate84725812010-02-04 15:52:40 -0800999 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001000 // backed up at least once
1001 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001002 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1003
1004 synchronized (mEverStoredApps) {
1005 if (!mEverStoredApps.add(packageName)) return;
1006
1007 RandomAccessFile out = null;
1008 try {
1009 out = new RandomAccessFile(mEverStored, "rws");
1010 out.seek(out.length());
1011 out.writeUTF(packageName);
1012 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001013 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001014 } finally {
1015 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001016 }
1017 }
1018 }
1019
Christopher Tatee97e8072009-07-15 16:45:50 -07001020 // Remove our awareness of having ever backed up the given package
1021 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001022 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001023
Dan Egnor852f8e42009-09-30 11:20:45 -07001024 synchronized (mEverStoredApps) {
1025 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1026 // we'll recognize on initialization time that the package no longer
1027 // exists and fix it up then.
1028 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1029 RandomAccessFile known = null;
1030 try {
1031 known = new RandomAccessFile(tempKnownFile, "rws");
1032 mEverStoredApps.remove(packageName);
1033 for (String s : mEverStoredApps) {
1034 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001035 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001036 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001037 known.close();
1038 known = null;
1039 if (!tempKnownFile.renameTo(mEverStored)) {
1040 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1041 }
1042 } catch (IOException e) {
1043 // Bad: we couldn't create the new copy. For safety's sake we
1044 // abandon the whole process and remove all what's-backed-up
1045 // state entirely, meaning we'll force a backup pass for every
1046 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001048 mEverStoredApps.clear();
1049 tempKnownFile.delete();
1050 mEverStored.delete();
1051 } finally {
1052 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001053 }
1054 }
1055 }
1056
Christopher Tateb49ceb32010-02-08 16:22:24 -08001057 // Persistently record the current and ancestral backup tokens as well
1058 // as the set of packages with data [supposedly] available in the
1059 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001060 void writeRestoreTokens() {
1061 try {
1062 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001063
1064 // First, the version number of this record, for futureproofing
1065 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1066
1067 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001068 af.writeLong(mAncestralToken);
1069 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001070
1071 // Now write the set of ancestral packages
1072 if (mAncestralPackages == null) {
1073 af.writeInt(-1);
1074 } else {
1075 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001076 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001077 for (String pkgName : mAncestralPackages) {
1078 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001080 }
1081 }
Christopher Tate84725812010-02-04 15:52:40 -08001082 af.close();
1083 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001084 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001085 }
1086 }
1087
Dan Egnor87a02bc2009-06-17 02:30:10 -07001088 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001089 private IBackupTransport getTransport(String transportName) {
1090 synchronized (mTransports) {
1091 IBackupTransport transport = mTransports.get(transportName);
1092 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001093 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001094 }
1095 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001096 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001097 }
1098
Christopher Tatedf01dea2009-06-09 20:45:02 -07001099 // fire off a backup agent, blocking until it attaches or times out
1100 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1101 IBackupAgent agent = null;
1102 synchronized(mAgentConnectLock) {
1103 mConnecting = true;
1104 mConnectedAgent = null;
1105 try {
1106 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001107 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001108
1109 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001110 // only wait 10 seconds for the clear data to happen
1111 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1112 while (mConnecting && mConnectedAgent == null
1113 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001114 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001115 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001116 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001117 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001118 return null;
1119 }
1120 }
1121
1122 // if we timed out with no connect, abort and move on
1123 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001124 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001125 return null;
1126 }
1127 agent = mConnectedAgent;
1128 }
1129 } catch (RemoteException e) {
1130 // can't happen
1131 }
1132 }
1133 return agent;
1134 }
1135
Christopher Tatec7b31e32009-06-10 15:49:30 -07001136 // clear an application's data, blocking until the operation completes or times out
1137 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001138 // Don't wipe packages marked allowClearUserData=false
1139 try {
1140 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1141 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001142 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001143 + packageName);
1144 return;
1145 }
1146 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001147 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001148 return;
1149 }
1150
Christopher Tatec7b31e32009-06-10 15:49:30 -07001151 ClearDataObserver observer = new ClearDataObserver();
1152
1153 synchronized(mClearDataLock) {
1154 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001155 try {
1156 mActivityManager.clearApplicationUserData(packageName, observer);
1157 } catch (RemoteException e) {
1158 // can't happen because the activity manager is in this process
1159 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001160
1161 // only wait 10 seconds for the clear data to happen
1162 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1163 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1164 try {
1165 mClearDataLock.wait(5000);
1166 } catch (InterruptedException e) {
1167 // won't happen, but still.
1168 mClearingData = false;
1169 }
1170 }
1171 }
1172 }
1173
1174 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001175 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001176 synchronized(mClearDataLock) {
1177 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001178 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001179 }
1180 }
1181 }
1182
Christopher Tate1bb69062010-02-19 17:02:12 -08001183 // Get the restore-set token for the best-available restore set for this package:
1184 // the active set if possible, else the ancestral one. Returns zero if none available.
1185 long getAvailableRestoreToken(String packageName) {
1186 long token = mAncestralToken;
1187 synchronized (mQueueLock) {
1188 if (mEverStoredApps.contains(packageName)) {
1189 token = mCurrentToken;
1190 }
1191 }
1192 return token;
1193 }
1194
Christopher Tate44a27902010-01-27 17:15:49 -08001195 // -----
1196 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1197 boolean waitUntilOperationComplete(int token) {
1198 int finalState = OP_PENDING;
1199 synchronized (mCurrentOpLock) {
1200 try {
1201 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1202 try {
1203 mCurrentOpLock.wait();
1204 } catch (InterruptedException e) {}
1205 }
1206 } catch (IndexOutOfBoundsException e) {
1207 // the operation has been mysteriously cleared from our
1208 // bookkeeping -- consider this a success and ignore it.
1209 }
1210 }
1211 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001212 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001213 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001214 return finalState == OP_ACKNOWLEDGED;
1215 }
1216
1217 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001218 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001219 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001220 mCurrentOperations.put(token, OP_PENDING);
1221 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1222 mBackupHandler.sendMessageDelayed(msg, interval);
1223 }
1224
Christopher Tate043dadc2009-06-02 16:11:00 -07001225 // ----- Back up a set of applications via a worker thread -----
1226
Christopher Tate44a27902010-01-27 17:15:49 -08001227 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001228 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001229 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001230 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001231 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001232 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001233
Christopher Tate44a27902010-01-27 17:15:49 -08001234 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001235 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001236 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001237 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001238 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001239
1240 try {
1241 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1242 } catch (RemoteException e) {
1243 // can't happen; the transport is local
1244 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001245 }
1246
Christopher Tate043dadc2009-06-02 16:11:00 -07001247 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001248 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001249 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001250 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001251
Christopher Tate79588342009-06-30 16:11:49 -07001252 // Backups run at background priority
1253 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1254
Christopher Tate043dadc2009-06-02 16:11:00 -07001255 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001256 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001257
Dan Egnor852f8e42009-09-30 11:20:45 -07001258 // If we haven't stored package manager metadata yet, we must init the transport.
1259 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1260 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001261 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001262 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001263 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001264 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001265 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001266 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001267 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001268 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001269 }
Dan Egnor01445162009-09-21 17:04:05 -07001270 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001271
1272 // The package manager doesn't have a proper <application> etc, but since
1273 // it's running here in the system process we can just set up its agent
1274 // directly and use a synthetic BackupRequest. We always run this pass
1275 // because it's cheap and this way we guarantee that we don't get out of
1276 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001277 if (status == BackupConstants.TRANSPORT_OK) {
1278 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1279 mPackageManager, allAgentPackages());
1280 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1281 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1282 status = processOneBackup(pmRequest,
1283 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1284 }
Christopher Tate90967f42009-09-20 15:28:33 -07001285
Dan Egnor01445162009-09-21 17:04:05 -07001286 if (status == BackupConstants.TRANSPORT_OK) {
1287 // Now run all the backups in our queue
1288 status = doQueuedBackups(mTransport);
1289 }
1290
1291 if (status == BackupConstants.TRANSPORT_OK) {
1292 // Tell the transport to finish everything it has buffered
1293 status = mTransport.finishBackup();
1294 if (status == BackupConstants.TRANSPORT_OK) {
1295 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001296 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001297 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001298 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001299 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001300 }
1301 }
1302
Dan Egnor01445162009-09-21 17:04:05 -07001303 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001304 // The backend reports that our dataset has been wiped. We need to
1305 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001306 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001307 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001308 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001309 }
1310 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001311 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001312 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001313 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001314 // If everything actually went through and this is the first time we've
1315 // done a backup, we can now record what the current backup dataset token
1316 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001317 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001318 try {
1319 mCurrentToken = mTransport.getCurrentRestoreSet();
1320 } catch (RemoteException e) { /* cannot happen */ }
1321 writeRestoreTokens();
1322 }
1323
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001324 // If things went wrong, we need to re-stage the apps we had expected
1325 // to be backing up in this pass. This journals the package names in
1326 // the current active pending-backup file, not in the we are holding
1327 // here in mJournal.
1328 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001329 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001330 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001331 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001332 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001333
1334 // We also want to reset the backup schedule based on whatever
1335 // the transport suggests by way of retry/backoff time.
1336 try {
1337 startBackupAlarmsLocked(mTransport.requestBackupTime());
1338 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001339 }
1340
1341 // Either backup was successful, in which case we of course do not need
1342 // this pass's journal any more; or it failed, in which case we just
1343 // re-enqueued all of these packages in the current active journal.
1344 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001345 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001346 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001347 }
1348
Christopher Tatec2af5d32010-02-02 15:18:58 -08001349 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001350 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001351 backupNow();
1352 }
1353
Dan Egnorbb9001c2009-07-27 12:20:13 -07001354 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001355 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001356 }
1357
Dan Egnor01445162009-09-21 17:04:05 -07001358 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001359 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001360 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001361
1362 IBackupAgent agent = null;
1363 int mode = (request.fullBackup)
1364 ? IApplicationThread.BACKUP_MODE_FULL
1365 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1366 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001367 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001368 agent = bindToAgentSynchronous(request.appInfo, mode);
1369 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001370 int result = processOneBackup(request, agent, transport);
1371 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001372 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001373 } catch (SecurityException ex) {
1374 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001375 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001376 } finally {
1377 try { // unbind even on timeout, just in case
1378 mActivityManager.unbindBackupAgent(request.appInfo);
1379 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001380 }
1381 }
Dan Egnor01445162009-09-21 17:04:05 -07001382
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001383 mWakelock.setWorkSource(null);
1384
Dan Egnor01445162009-09-21 17:04:05 -07001385 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001386 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001387
Dan Egnor01445162009-09-21 17:04:05 -07001388 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1389 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001390 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001391 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001392
Dan Egnorbb9001c2009-07-27 12:20:13 -07001393 File savedStateName = new File(mStateDir, packageName);
1394 File backupDataName = new File(mDataDir, packageName + ".data");
1395 File newStateName = new File(mStateDir, packageName + ".new");
1396
1397 ParcelFileDescriptor savedState = null;
1398 ParcelFileDescriptor backupData = null;
1399 ParcelFileDescriptor newState = null;
1400
1401 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001402 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001403 try {
1404 // Look up the package info & signatures. This is first so that if it
1405 // throws an exception, there's no file setup yet that would need to
1406 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001407 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1408 // The metadata 'package' is synthetic
1409 packInfo = new PackageInfo();
1410 packInfo.packageName = packageName;
1411 } else {
1412 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001413 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001414 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001415
Christopher Tatec7b31e32009-06-10 15:49:30 -07001416 // In a full backup, we pass a null ParcelFileDescriptor as
1417 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001418 if (!request.fullBackup) {
1419 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001420 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1422 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001423
Dan Egnorbb9001c2009-07-27 12:20:13 -07001424 backupData = ParcelFileDescriptor.open(backupDataName,
1425 ParcelFileDescriptor.MODE_READ_WRITE |
1426 ParcelFileDescriptor.MODE_CREATE |
1427 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001428
Dan Egnorbb9001c2009-07-27 12:20:13 -07001429 newState = ParcelFileDescriptor.open(newStateName,
1430 ParcelFileDescriptor.MODE_READ_WRITE |
1431 ParcelFileDescriptor.MODE_CREATE |
1432 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001433
Christopher Tate44a27902010-01-27 17:15:49 -08001434 // Initiate the target's backup pass
1435 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1436 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1437 boolean success = waitUntilOperationComplete(token);
1438
1439 if (!success) {
1440 // timeout -- bail out into the failed-transaction logic
1441 throw new RuntimeException("Backup timeout");
1442 }
1443
Dan Egnorbb9001c2009-07-27 12:20:13 -07001444 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001445 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001446 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001447 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001448 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001449 backupDataName.delete();
1450 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001451 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001452 } finally {
1453 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1454 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1455 try { if (newState != null) newState.close(); } catch (IOException e) {}
1456 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001457 synchronized (mCurrentOpLock) {
1458 mCurrentOperations.clear();
1459 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001460 }
1461
1462 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001463 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001464 try {
1465 int size = (int) backupDataName.length();
1466 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001467 if (result == BackupConstants.TRANSPORT_OK) {
1468 backupData = ParcelFileDescriptor.open(backupDataName,
1469 ParcelFileDescriptor.MODE_READ_ONLY);
1470 result = transport.performBackup(packInfo, backupData);
1471 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001472
Dan Egnor83861e72009-09-17 16:17:55 -07001473 // TODO - We call finishBackup() for each application backed up, because
1474 // we need to know now whether it succeeded or failed. Instead, we should
1475 // hold off on finishBackup() until the end, which implies holding off on
1476 // renaming *all* the output state files (see below) until that happens.
1477
Dan Egnor01445162009-09-21 17:04:05 -07001478 if (result == BackupConstants.TRANSPORT_OK) {
1479 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001480 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001481 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001482 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001483 }
1484
1485 // After successful transport, delete the now-stale data
1486 // and juggle the files so that next time we supply the agent
1487 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001488 if (result == BackupConstants.TRANSPORT_OK) {
1489 backupDataName.delete();
1490 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001492 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001493 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001494 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001495 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001496 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001497 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001498 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001499 } finally {
1500 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001501 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001502
Dan Egnor01445162009-09-21 17:04:05 -07001503 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001504 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001505 }
1506
Christopher Tatedf01dea2009-06-09 20:45:02 -07001507
1508 // ----- Restore handling -----
1509
Christopher Tate78dd4a72009-11-04 11:49:08 -08001510 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1511 // If the target resides on the system partition, we allow it to restore
1512 // data from the like-named package in a restore set even if the signatures
1513 // do not match. (Unlike general applications, those flashed to the system
1514 // partition will be signed with the device's platform certificate, so on
1515 // different phones the same system app will have different signatures.)
1516 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001518 return true;
1519 }
1520
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001521 // Allow unsigned apps, but not signed on one device and unsigned on the other
1522 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001523 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001525 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001526 if ((storedSigs == null || storedSigs.length == 0)
1527 && (deviceSigs == null || deviceSigs.length == 0)) {
1528 return true;
1529 }
1530 if (storedSigs == null || deviceSigs == null) {
1531 return false;
1532 }
1533
Christopher Tateabce4e82009-06-18 18:35:32 -07001534 // !!! TODO: this demands that every stored signature match one
1535 // that is present on device, and does not demand the converse.
1536 // Is this this right policy?
1537 int nStored = storedSigs.length;
1538 int nDevice = deviceSigs.length;
1539
1540 for (int i=0; i < nStored; i++) {
1541 boolean match = false;
1542 for (int j=0; j < nDevice; j++) {
1543 if (storedSigs[i].equals(deviceSigs[j])) {
1544 match = true;
1545 break;
1546 }
1547 }
1548 if (!match) {
1549 return false;
1550 }
1551 }
1552 return true;
1553 }
1554
Christopher Tate44a27902010-01-27 17:15:49 -08001555 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001557 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001558 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001559 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001560 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001561 private int mPmToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001562
Christopher Tate5cbbf562009-06-22 16:44:51 -07001563 class RestoreRequest {
1564 public PackageInfo app;
1565 public int storedAppVersion;
1566
1567 RestoreRequest(PackageInfo _app, int _version) {
1568 app = _app;
1569 storedAppVersion = _version;
1570 }
1571 }
1572
Christopher Tate44a27902010-01-27 17:15:49 -08001573 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate1bb69062010-02-19 17:02:12 -08001574 long restoreSetToken, PackageInfo targetPackage, int pmToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001575 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001576 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001577 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001578 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001579 mPmToken = pmToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001580
1581 try {
1582 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1583 } catch (RemoteException e) {
1584 // can't happen; the transport is local
1585 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001586 }
1587
Christopher Tatedf01dea2009-06-09 20:45:02 -07001588 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001589 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001590 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001591 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001592 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001593
Christopher Tateb49ceb32010-02-08 16:22:24 -08001594 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001595 int error = -1; // assume error
1596
Dan Egnorefe52642009-06-24 00:16:33 -07001597 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001598 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001600 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001601
Dan Egnorefe52642009-06-24 00:16:33 -07001602 // Get the list of all packages which have backup enabled.
1603 // (Include the Package Manager metadata pseudo-package first.)
1604 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1605 PackageInfo omPackage = new PackageInfo();
1606 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1607 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001608
Dan Egnorefe52642009-06-24 00:16:33 -07001609 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001610 if (mTargetPackage == null) {
1611 restorePackages.addAll(agentPackages);
1612 } else {
1613 // Just one package to attempt restore of
1614 restorePackages.add(mTargetPackage);
1615 }
Dan Egnorefe52642009-06-24 00:16:33 -07001616
Christopher Tate7d562ec2009-06-25 18:03:43 -07001617 // let the observer know that we're running
1618 if (mObserver != null) {
1619 try {
1620 // !!! TODO: get an actual count from the transport after
1621 // its startRestore() runs?
1622 mObserver.restoreStarting(restorePackages.size());
1623 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001625 mObserver = null;
1626 }
1627 }
1628
Dan Egnor01445162009-09-21 17:04:05 -07001629 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1630 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001631 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001632 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001633 return;
1634 }
1635
1636 String packageName = mTransport.nextRestorePackage();
1637 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001639 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001640 return;
1641 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001642 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001643 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001644 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001645 return;
1646 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001648 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001649 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001650 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001651 return;
1652 }
1653
1654 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001655 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001656 mPackageManager, agentPackages);
1657 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1658
Christopher Tate8c032472009-07-02 14:28:47 -07001659 // Verify that the backup set includes metadata. If not, we can't do
1660 // signature/version verification etc, so we simply do not proceed with
1661 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001662 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001663 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001664 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001665 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001666 return;
1667 }
1668
Christopher Tate7d562ec2009-06-25 18:03:43 -07001669 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001670 for (;;) {
1671 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001672
Dan Egnorefe52642009-06-24 00:16:33 -07001673 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001675 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001676 return;
1677 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001678 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001679 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001680 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001681
Christopher Tate7d562ec2009-06-25 18:03:43 -07001682 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001683 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001684 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001685 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001686 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001687 mObserver = null;
1688 }
1689 }
1690
Dan Egnorefe52642009-06-24 00:16:33 -07001691 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1692 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001693 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001694 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001695 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001696 continue;
1697 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001698
Dan Egnorbb9001c2009-07-27 12:20:13 -07001699 PackageInfo packageInfo;
1700 try {
1701 int flags = PackageManager.GET_SIGNATURES;
1702 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1703 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001704 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001705 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001706 "Package missing on device");
1707 continue;
1708 }
1709
Dan Egnorefe52642009-06-24 00:16:33 -07001710 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001711 // Data is from a "newer" version of the app than we have currently
1712 // installed. If the app has not declared that it is prepared to
1713 // handle this case, we do not attempt the restore.
1714 if ((packageInfo.applicationInfo.flags
1715 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1716 String message = "Version " + metaInfo.versionCode
1717 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001718 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001719 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1720 packageName, message);
1721 continue;
1722 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001723 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001724 + " > installed " + packageInfo.versionCode
1725 + " but restoreAnyVersion");
1726 }
Dan Egnorefe52642009-06-24 00:16:33 -07001727 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001728
Christopher Tate78dd4a72009-11-04 11:49:08 -08001729 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001730 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001731 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001732 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001733 continue;
1734 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001735
Joe Onorato8a9b2202010-02-26 18:56:32 -08001736 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001737 + " restore version [" + metaInfo.versionCode
1738 + "] is compatible with installed version ["
1739 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001740
Christopher Tate3de55bc2010-03-12 17:28:08 -08001741 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001742 IBackupAgent agent = bindToAgentSynchronous(
1743 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001744 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001745 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001747 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001748 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001749 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001750 }
1751
Christopher Tate5e1ab332009-09-01 20:32:49 -07001752 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001753 try {
1754 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001755 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001756 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001757 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001758 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001759
1760 // The agent was probably running with a stub Application object,
1761 // which isn't a valid run mode for the main app logic. Shut
1762 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001763 // usual full initialization. Note that this is only done for
1764 // full-system restores: when a single app has requested a restore,
1765 // it is explicitly not killed following that operation.
1766 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001767 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001768 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001769 + packageInfo.applicationInfo.processName);
1770 mActivityManager.killApplicationProcess(
1771 packageInfo.applicationInfo.processName,
1772 packageInfo.applicationInfo.uid);
1773 }
Dan Egnorefe52642009-06-24 00:16:33 -07001774 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001775 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001776
1777 // if we get this far, report success to the observer
1778 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001779 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001780 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001781 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001782 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001783 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001784 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001785
Dan Egnorefe52642009-06-24 00:16:33 -07001786 try {
1787 mTransport.finishRestore();
1788 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001789 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001790 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001791
1792 if (mObserver != null) {
1793 try {
1794 mObserver.restoreFinished(error);
1795 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001796 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001797 }
1798 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001799
Christopher Tate84725812010-02-04 15:52:40 -08001800 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001801 // ancestral dataset, as well as the set of apps that are possibly
1802 // restoreable from the dataset
1803 if (mTargetPackage == null && pmAgent != null) {
1804 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001805 mAncestralToken = mToken;
1806 writeRestoreTokens();
1807 }
1808
Christopher Tate1bb69062010-02-19 17:02:12 -08001809 // We must under all circumstances tell the Package Manager to
1810 // proceed with install notifications if it's waiting for us.
1811 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001812 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001813 try {
1814 mPackageManagerBinder.finishPackageInstall(mPmToken);
1815 } catch (RemoteException e) { /* can't happen */ }
1816 }
1817
Christopher Tateb6787f22009-07-02 17:40:45 -07001818 // done; we can finally release the wakelock
1819 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001820 }
1821 }
1822
Dan Egnorefe52642009-06-24 00:16:33 -07001823 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1824 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001825 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001826 final String packageName = app.packageName;
1827
Joe Onorato8a9b2202010-02-26 18:56:32 -08001828 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001829
Christopher Tatec7b31e32009-06-10 15:49:30 -07001830 // !!! TODO: get the dirs from the transport
1831 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001832 File newStateName = new File(mStateDir, packageName + ".new");
1833 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001834
Dan Egnorbb9001c2009-07-27 12:20:13 -07001835 ParcelFileDescriptor backupData = null;
1836 ParcelFileDescriptor newState = null;
1837
Christopher Tate44a27902010-01-27 17:15:49 -08001838 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001839 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001840 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001841 backupData = ParcelFileDescriptor.open(backupDataName,
1842 ParcelFileDescriptor.MODE_READ_WRITE |
1843 ParcelFileDescriptor.MODE_CREATE |
1844 ParcelFileDescriptor.MODE_TRUNCATE);
1845
Dan Egnor01445162009-09-21 17:04:05 -07001846 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001847 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001848 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001849 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001850 }
1851
1852 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001854 backupData = ParcelFileDescriptor.open(backupDataName,
1855 ParcelFileDescriptor.MODE_READ_ONLY);
1856
Dan Egnorbb9001c2009-07-27 12:20:13 -07001857 newState = ParcelFileDescriptor.open(newStateName,
1858 ParcelFileDescriptor.MODE_READ_WRITE |
1859 ParcelFileDescriptor.MODE_CREATE |
1860 ParcelFileDescriptor.MODE_TRUNCATE);
1861
Christopher Tate44a27902010-01-27 17:15:49 -08001862 // Kick off the restore, checking for hung agents
1863 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1864 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1865 boolean success = waitUntilOperationComplete(token);
1866
1867 if (!success) {
1868 throw new RuntimeException("restore timeout");
1869 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001870
1871 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001872 //
1873 // !!! TODO: the restored data should be migrated on the server
1874 // side into the current dataset. In that case the new state file
1875 // we just created would reflect the data already extant in the
1876 // backend, so there'd be nothing more to do. Until that happens,
1877 // however, we need to make sure that we record the data to the
1878 // current backend dataset. (Yes, this means shipping the data over
1879 // the wire in both directions. That's bad, but consistency comes
1880 // first, then efficiency.) Once we introduce server-side data
1881 // migration to the newly-restored device's dataset, we will change
1882 // the following from a discard of the newly-written state to the
1883 // "correct" operation of renaming into the canonical state blob.
1884 newStateName.delete(); // TODO: remove; see above comment
1885 //newStateName.renameTo(savedStateName); // TODO: replace with this
1886
Dan Egnorbb9001c2009-07-27 12:20:13 -07001887 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001888 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001889 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001890 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001891 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001892
Christopher Tate96733042009-07-20 14:49:13 -07001893 // If the agent fails restore, it might have put the app's data
1894 // into an incoherent state. For consistency we wipe its data
1895 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001896 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001897 } finally {
1898 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001899 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1900 try { if (newState != null) newState.close(); } catch (IOException e) {}
1901 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001902 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001903 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001904 }
1905 }
1906
Christopher Tate44a27902010-01-27 17:15:49 -08001907 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001908 IBackupTransport mTransport;
1909 PackageInfo mPackage;
1910
Christopher Tate44a27902010-01-27 17:15:49 -08001911 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001912 mTransport = transport;
1913 mPackage = packageInfo;
1914 }
1915
Christopher Tateee0e78a2009-07-02 11:17:03 -07001916 public void run() {
1917 try {
1918 // Clear the on-device backup state to ensure a full backup next time
1919 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1920 File stateFile = new File(stateDir, mPackage.packageName);
1921 stateFile.delete();
1922
1923 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001924 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001925 mTransport.clearBackupData(mPackage);
1926 } catch (RemoteException e) {
1927 // can't happen; the transport is local
1928 } finally {
1929 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001930 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001931 mTransport.finishBackup();
1932 } catch (RemoteException e) {
1933 // can't happen; the transport is local
1934 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001935
1936 // Last but not least, release the cpu
1937 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001938 }
1939 }
1940 }
1941
Christopher Tate44a27902010-01-27 17:15:49 -08001942 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001943 HashSet<String> mQueue;
1944
Christopher Tate44a27902010-01-27 17:15:49 -08001945 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001946 mQueue = transportNames;
1947 }
1948
Christopher Tate4cc86e12009-09-21 19:36:51 -07001949 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001950 try {
1951 for (String transportName : mQueue) {
1952 IBackupTransport transport = getTransport(transportName);
1953 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001954 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001955 continue;
1956 }
1957
Joe Onorato8a9b2202010-02-26 18:56:32 -08001958 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001959 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001960 long startRealtime = SystemClock.elapsedRealtime();
1961 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001962
Christopher Tate4cc86e12009-09-21 19:36:51 -07001963 if (status == BackupConstants.TRANSPORT_OK) {
1964 status = transport.finishBackup();
1965 }
1966
1967 // Okay, the wipe really happened. Clean up our local bookkeeping.
1968 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001969 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001970 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001971 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001972 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001973 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001974 synchronized (mQueueLock) {
1975 recordInitPendingLocked(false, transportName);
1976 }
Dan Egnor726247c2009-09-29 19:12:31 -07001977 } else {
1978 // If this didn't work, requeue this one and try again
1979 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08001980 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001981 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001982 synchronized (mQueueLock) {
1983 recordInitPendingLocked(true, transportName);
1984 }
1985 // do this via another alarm to make sure of the wakelock states
1986 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001987 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07001988 + transportName + " resched in " + delay);
1989 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1990 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001991 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001992 }
1993 } catch (RemoteException e) {
1994 // can't happen; the transports are local
1995 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001996 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001997 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001998 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001999 mWakelock.release();
2000 }
2001 }
2002 }
2003
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002004 private void dataChangedImpl(String packageName) {
2005 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2006 dataChangedImpl(packageName, targets);
2007 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002008
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002009 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002010 // Record that we need a backup pass for the caller. Since multiple callers
2011 // may share a uid, we need to note all candidates within that uid and schedule
2012 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002013 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002014
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002015 if (targets == null) {
2016 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2017 + " uid=" + Binder.getCallingUid());
2018 return;
2019 }
2020
2021 synchronized (mQueueLock) {
2022 // Note that this client has made data changes that need to be backed up
2023 for (ApplicationInfo app : targets) {
2024 // validate the caller-supplied package name against the known set of
2025 // packages associated with this uid
2026 if (app.packageName.equals(packageName)) {
2027 // Add the caller to the set of pending backups. If there is
2028 // one already there, then overwrite it, but no harm done.
2029 BackupRequest req = new BackupRequest(app, false);
2030 if (mPendingBackups.put(app, req) == null) {
2031 // Journal this request in case of crash. The put()
2032 // operation returned null when this package was not already
2033 // in the set; we want to avoid touching the disk redundantly.
2034 writeToJournalLocked(packageName);
2035
2036 if (DEBUG) {
2037 int numKeys = mPendingBackups.size();
2038 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2039 for (BackupRequest b : mPendingBackups.values()) {
2040 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2041 }
2042 }
2043 }
2044 }
2045 }
2046 }
2047 }
2048
2049 // Note: packageName is currently unused, but may be in the future
2050 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002051 // If the caller does not hold the BACKUP permission, it can only request a
2052 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002053 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002054 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002055 synchronized (mBackupParticipants) {
2056 return mBackupParticipants.get(Binder.getCallingUid());
2057 }
2058 }
2059
2060 // a caller with full permission can ask to back up any participating app
2061 // !!! TODO: allow backup of ANY app?
2062 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2063 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002064 int N = mBackupParticipants.size();
2065 for (int i = 0; i < N; i++) {
2066 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2067 if (s != null) {
2068 targets.addAll(s);
2069 }
2070 }
2071 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002072 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002073 }
Christopher Tate46758122009-05-06 11:22:00 -07002074
Christopher Tatecde87f42009-06-12 12:55:53 -07002075 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002076 RandomAccessFile out = null;
2077 try {
2078 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2079 out = new RandomAccessFile(mJournal, "rws");
2080 out.seek(out.length());
2081 out.writeUTF(str);
2082 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002083 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002084 mJournal = null;
2085 } finally {
2086 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002087 }
2088 }
2089
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002090 // ----- IBackupManager binder interface -----
2091
2092 public void dataChanged(final String packageName) {
2093 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2094 if (targets == null) {
2095 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2096 + " uid=" + Binder.getCallingUid());
2097 return;
2098 }
2099
2100 mBackupHandler.post(new Runnable() {
2101 public void run() {
2102 dataChangedImpl(packageName, targets);
2103 }
2104 });
2105 }
2106
Christopher Tateee0e78a2009-07-02 11:17:03 -07002107 // Clear the given package's backup data from the current transport
2108 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002109 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002110 PackageInfo info;
2111 try {
2112 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2113 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002114 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002115 return;
2116 }
2117
2118 // If the caller does not hold the BACKUP permission, it can only request a
2119 // wipe of its own backed-up data.
2120 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002121 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002122 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2123 apps = mBackupParticipants.get(Binder.getCallingUid());
2124 } else {
2125 // a caller with full permission can ask to back up any participating app
2126 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002127 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002128 apps = new HashSet<ApplicationInfo>();
2129 int N = mBackupParticipants.size();
2130 for (int i = 0; i < N; i++) {
2131 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2132 if (s != null) {
2133 apps.addAll(s);
2134 }
2135 }
2136 }
2137
2138 // now find the given package in the set of candidate apps
2139 for (ApplicationInfo app : apps) {
2140 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002141 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002142 // found it; fire off the clear request
2143 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002144 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002145 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002146 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2147 new ClearParams(getTransport(mCurrentTransport), info));
2148 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002149 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002150 }
2151 break;
2152 }
2153 }
2154 }
2155
Christopher Tateace7f092009-06-15 18:07:25 -07002156 // Run a backup pass immediately for any applications that have declared
2157 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002158 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002160
Joe Onorato8a9b2202010-02-26 18:56:32 -08002161 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002162 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002163 // Because the alarms we are using can jitter, and we want an *immediate*
2164 // backup pass to happen, we restart the timer beginning with "next time,"
2165 // then manually fire the backup trigger intent ourselves.
2166 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002167 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002168 mRunBackupIntent.send();
2169 } catch (PendingIntent.CanceledException e) {
2170 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002171 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002172 }
Christopher Tate46758122009-05-06 11:22:00 -07002173 }
2174 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002175
Christopher Tate8031a3d2009-07-06 16:36:05 -07002176 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002177 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2179 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002180
Joe Onorato8a9b2202010-02-26 18:56:32 -08002181 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002182
Christopher Tate6ef58a12009-06-29 14:56:28 -07002183 boolean wasEnabled = mEnabled;
2184 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002185 Settings.Secure.putInt(mContext.getContentResolver(),
2186 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002187 mEnabled = enable;
2188 }
2189
Christopher Tate49401dd2009-07-01 12:34:29 -07002190 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002191 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002192 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002193 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002194 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002195 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002196 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002197
Christopher Tateb6787f22009-07-02 17:40:45 -07002198 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002199
2200 // This also constitutes an opt-out, so we wipe any data for
2201 // this device from the backend. We start that process with
2202 // an alarm in order to guarantee wakelock states.
2203 if (wasEnabled && mProvisioned) {
2204 // NOTE: we currently flush every registered transport, not just
2205 // the currently-active one.
2206 HashSet<String> allTransports;
2207 synchronized (mTransports) {
2208 allTransports = new HashSet<String>(mTransports.keySet());
2209 }
2210 // build the set of transports for which we are posting an init
2211 for (String transport : allTransports) {
2212 recordInitPendingLocked(true, transport);
2213 }
2214 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2215 mRunInitIntent);
2216 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002217 }
2218 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002219 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002220
Christopher Tatecce9da52010-02-03 15:11:15 -08002221 // Enable/disable automatic restore of app data at install time
2222 public void setAutoRestore(boolean doAutoRestore) {
2223 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2224 "setBackupEnabled");
2225
Joe Onorato8a9b2202010-02-26 18:56:32 -08002226 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002227
2228 synchronized (this) {
2229 Settings.Secure.putInt(mContext.getContentResolver(),
2230 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2231 mAutoRestore = doAutoRestore;
2232 }
2233 }
2234
Christopher Tate8031a3d2009-07-06 16:36:05 -07002235 // Mark the backup service as having been provisioned
2236 public void setBackupProvisioned(boolean available) {
2237 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2238 "setBackupProvisioned");
2239
2240 boolean wasProvisioned = mProvisioned;
2241 synchronized (this) {
2242 Settings.Secure.putInt(mContext.getContentResolver(),
2243 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2244 mProvisioned = available;
2245 }
2246
2247 synchronized (mQueueLock) {
2248 if (available && !wasProvisioned && mEnabled) {
2249 // we're now good to go, so start the backup alarms
2250 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2251 } else if (!available) {
2252 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002253 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002254 mAlarmManager.cancel(mRunBackupIntent);
2255 }
2256 }
2257 }
2258
2259 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002260 // We used to use setInexactRepeating(), but that may be linked to
2261 // backups running at :00 more often than not, creating load spikes.
2262 // Schedule at an exact time for now, and also add a bit of "fuzz".
2263
2264 Random random = new Random();
2265 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2266 random.nextInt(FUZZ_MILLIS);
2267 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2268 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002269 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002270 }
2271
Christopher Tate6ef58a12009-06-29 14:56:28 -07002272 // Report whether the backup mechanism is currently enabled
2273 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002274 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002275 return mEnabled; // no need to synchronize just to read it
2276 }
2277
Christopher Tate91717492009-06-26 21:07:13 -07002278 // Report the name of the currently active transport
2279 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002280 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002281 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002282 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002283 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002284 }
2285
Christopher Tate91717492009-06-26 21:07:13 -07002286 // Report all known, available backup transports
2287 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002289
Christopher Tate91717492009-06-26 21:07:13 -07002290 String[] list = null;
2291 ArrayList<String> known = new ArrayList<String>();
2292 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2293 if (entry.getValue() != null) {
2294 known.add(entry.getKey());
2295 }
2296 }
2297
2298 if (known.size() > 0) {
2299 list = new String[known.size()];
2300 known.toArray(list);
2301 }
2302 return list;
2303 }
2304
2305 // Select which transport to use for the next backup operation. If the given
2306 // name is not one of the available transports, no action is taken and the method
2307 // returns null.
2308 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002309 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002310
2311 synchronized (mTransports) {
2312 String prevTransport = null;
2313 if (mTransports.get(transport) != null) {
2314 prevTransport = mCurrentTransport;
2315 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002316 Settings.Secure.putString(mContext.getContentResolver(),
2317 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002318 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002319 + " returning " + prevTransport);
2320 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002321 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002322 }
2323 return prevTransport;
2324 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002325 }
2326
2327 // Callback: a requested backup agent has been instantiated. This should only
2328 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002329 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002330 synchronized(mAgentConnectLock) {
2331 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002332 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002333 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2334 mConnectedAgent = agent;
2335 mConnecting = false;
2336 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002337 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002338 + " claiming agent connected");
2339 }
2340 mAgentConnectLock.notifyAll();
2341 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002342 }
2343
2344 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2345 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002346 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002347 public void agentDisconnected(String packageName) {
2348 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002349 synchronized(mAgentConnectLock) {
2350 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2351 mConnectedAgent = null;
2352 mConnecting = false;
2353 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002354 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002355 + " claiming agent disconnected");
2356 }
2357 mAgentConnectLock.notifyAll();
2358 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002359 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002360
Christopher Tate1bb69062010-02-19 17:02:12 -08002361 // An application being installed will need a restore pass, then the Package Manager
2362 // will need to be told when the restore is finished.
2363 public void restoreAtInstall(String packageName, int token) {
2364 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002365 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002366 + " attemping install-time restore");
2367 return;
2368 }
2369
2370 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002371 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002372 + " token=" + Integer.toHexString(token));
2373
Christopher Tatef0872722010-02-25 15:22:48 -08002374 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002375 // okay, we're going to attempt a restore of this package from this restore set.
2376 // The eventual message back into the Package Manager to run the post-install
2377 // steps for 'token' will be issued from the restore handling code.
2378
2379 // We can use a synthetic PackageInfo here because:
2380 // 1. We know it's valid, since the Package Manager supplied the name
2381 // 2. Only the packageName field will be used by the restore code
2382 PackageInfo pkg = new PackageInfo();
2383 pkg.packageName = packageName;
2384
2385 mWakelock.acquire();
2386 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2387 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2388 restoreSet, pkg, token);
2389 mBackupHandler.sendMessage(msg);
2390 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002391 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2392 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002393 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002394 try {
2395 mPackageManagerBinder.finishPackageInstall(token);
2396 } catch (RemoteException e) { /* can't happen */ }
2397 }
2398 }
2399
Christopher Tate8c850b72009-06-07 19:33:20 -07002400 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002401 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002402 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002403
2404 synchronized(this) {
2405 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002406 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002407 return null;
2408 }
Christopher Tate80202c82010-01-25 19:37:47 -08002409 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002410 }
2411 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002412 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002413
Christopher Tate44a27902010-01-27 17:15:49 -08002414 // Note that a currently-active backup agent has notified us that it has
2415 // completed the given outstanding asynchronous backup/restore operation.
2416 public void opComplete(int token) {
2417 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002418 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002419 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2420 mCurrentOpLock.notifyAll();
2421 }
2422 }
2423
Christopher Tate9b3905c2009-06-08 15:24:01 -07002424 // ----- Restore session -----
2425
Christopher Tate80202c82010-01-25 19:37:47 -08002426 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002427 private static final String TAG = "RestoreSession";
2428
Christopher Tate9b3905c2009-06-08 15:24:01 -07002429 private IBackupTransport mRestoreTransport = null;
2430 RestoreSet[] mRestoreSets = null;
2431
Christopher Tate80202c82010-01-25 19:37:47 -08002432 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002433 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002434 }
2435
2436 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002437 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002439 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002440 if (observer == null) {
2441 throw new IllegalArgumentException("Observer must not be null");
2442 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002443
Christopher Tate1bb69062010-02-19 17:02:12 -08002444 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002445 try {
Christopher Tate43383042009-07-13 15:17:13 -07002446 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002447 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002448 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002449 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002450 // spin off the transport request to our service thread
2451 mWakelock.acquire();
2452 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2453 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2454 mBackupHandler.sendMessage(msg);
2455 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002456 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002457 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002458 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002459 } finally {
2460 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002461 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002462 }
2463
Christopher Tate84725812010-02-04 15:52:40 -08002464 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002465 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2466 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002467
Joe Onorato8a9b2202010-02-26 18:56:32 -08002468 if (DEBUG) Slog.d(TAG, "performRestore token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002469 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002470
Dan Egnor0084da52009-07-29 12:57:16 -07002471 if (mRestoreTransport == null || mRestoreSets == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002472 Slog.e(TAG, "Ignoring performRestore() with no restore set");
Dan Egnor0084da52009-07-29 12:57:16 -07002473 return -1;
2474 }
2475
Christopher Tate21ab6a52009-09-24 18:01:46 -07002476 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002477 for (int i = 0; i < mRestoreSets.length; i++) {
2478 if (token == mRestoreSets[i].token) {
2479 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002480 mWakelock.acquire();
2481 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2482 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2483 mBackupHandler.sendMessage(msg);
2484 Binder.restoreCallingIdentity(oldId);
2485 return 0;
2486 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002487 }
2488 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002489
Joe Onorato8a9b2202010-02-26 18:56:32 -08002490 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002491 return -1;
2492 }
2493
Christopher Tate84725812010-02-04 15:52:40 -08002494 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002495 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002496
2497 PackageInfo app = null;
2498 try {
2499 app = mPackageManager.getPackageInfo(packageName, 0);
2500 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002501 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002502 return -1;
2503 }
2504
2505 // If the caller is not privileged and is not coming from the target
2506 // app's uid, throw a permission exception back to the caller.
2507 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2508 Binder.getCallingPid(), Binder.getCallingUid());
2509 if ((perm == PackageManager.PERMISSION_DENIED) &&
2510 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002511 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002512 + " or calling uid=" + Binder.getCallingUid());
2513 throw new SecurityException("No permission to restore other packages");
2514 }
2515
Christopher Tate7d411a32010-02-26 11:27:08 -08002516 // If the package has no backup agent, we obviously cannot proceed
2517 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002518 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002519 return -1;
2520 }
2521
Christopher Tate84725812010-02-04 15:52:40 -08002522 // So far so good; we're allowed to try to restore this package. Now
2523 // check whether there is data for it in the current dataset, falling back
2524 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002525 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002526
2527 // If we didn't come up with a place to look -- no ancestral dataset and
2528 // the app has never been backed up from this device -- there's nothing
2529 // to do but return failure.
2530 if (token == 0) {
2531 return -1;
2532 }
2533
2534 // Ready to go: enqueue the restore request and claim success
2535 long oldId = Binder.clearCallingIdentity();
2536 mWakelock.acquire();
2537 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002538 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002539 mBackupHandler.sendMessage(msg);
2540 Binder.restoreCallingIdentity(oldId);
2541 return 0;
2542 }
2543
Dan Egnor0084da52009-07-29 12:57:16 -07002544 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002546 "endRestoreSession");
2547
Joe Onorato8a9b2202010-02-26 18:56:32 -08002548 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002549
Dan Egnor0084da52009-07-29 12:57:16 -07002550 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002551 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002552 try {
2553 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2554 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002555 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002556 } finally {
2557 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002558 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002559 }
2560 }
2561
2562 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002563 if (BackupManagerService.this.mActiveRestoreSession == this) {
2564 BackupManagerService.this.mActiveRestoreSession = null;
2565 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002566 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002567 }
2568 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002569 }
2570 }
2571
Christopher Tate043dadc2009-06-02 16:11:00 -07002572
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002573 @Override
2574 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2575 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002576 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002577 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002578 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002579 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002580 pw.println("Last backup pass: " + mLastBackupPass
2581 + " (now = " + System.currentTimeMillis() + ')');
2582 pw.println(" next scheduled: " + mNextBackupPass);
2583
Christopher Tate91717492009-06-26 21:07:13 -07002584 pw.println("Available transports:");
2585 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002586 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2587 try {
2588 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2589 for (File f : dir.listFiles()) {
2590 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2591 }
2592 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002593 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002594 pw.println(" Error: " + e);
2595 }
Christopher Tate91717492009-06-26 21:07:13 -07002596 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002597
2598 pw.println("Pending init: " + mPendingInits.size());
2599 for (String s : mPendingInits) {
2600 pw.println(" " + s);
2601 }
2602
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002603 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002604 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002605 for (int i=0; i<N; i++) {
2606 int uid = mBackupParticipants.keyAt(i);
2607 pw.print(" uid: ");
2608 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002609 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2610 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002611 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002612 }
2613 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002614
Christopher Tateb49ceb32010-02-08 16:22:24 -08002615 pw.println("Ancestral packages: "
2616 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002617 if (mAncestralPackages != null) {
2618 for (String pkg : mAncestralPackages) {
2619 pw.println(" " + pkg);
2620 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002621 }
2622
Christopher Tate73e02522009-07-15 14:18:26 -07002623 pw.println("Ever backed up: " + mEverStoredApps.size());
2624 for (String pkg : mEverStoredApps) {
2625 pw.println(" " + pkg);
2626 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002627
2628 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002629 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002630 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002631 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002632 }
2633 }
Christopher Tate487529a2009-04-29 14:03:25 -07002634}