blob: 455b4c209aa4d2b66f09cc19f0eabe0d880dbf79 [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 Tate4a627c72011-04-01 14:43:32 -070026import android.app.backup.BackupDataOutput;
27import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060028import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080029import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070030import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080031import android.app.backup.IRestoreObserver;
32import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070033import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070036import android.content.Context;
37import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070039import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070040import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070041import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080042import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070043import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070044import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060045import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060046import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070047import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070049import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070050import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080052import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080054import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070057import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070058import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070060import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070061import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080062import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070063import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080066import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070067import android.util.StringBuilderPrinter;
68
Jason parksa3cdaa52011-01-13 14:15:43 -060069import com.android.internal.backup.BackupConstants;
70import com.android.internal.backup.IBackupTransport;
71import com.android.internal.backup.LocalTransport;
72import com.android.server.PackageManagerBackupAgent.Metadata;
73
Christopher Tatecde87f42009-06-12 12:55:53 -070074import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070075import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070076import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080077import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070078import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070079import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070080import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070081import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040082import java.util.ArrayList;
83import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070084import java.util.HashSet;
85import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070086import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070087import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080088import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -070089import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate487529a2009-04-29 14:03:25 -070090
91class BackupManagerService extends IBackupManager.Stub {
92 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -070093 private static final boolean DEBUG = true;
94
95 // Name and current contents version of the full-backup manifest file
96 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
97 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -070098
Christopher Tate49401dd2009-07-01 12:34:29 -070099 // How often we perform a backup pass. Privileged external callers can
100 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700101 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700102
Dan Egnorc1c49c02009-10-30 17:35:39 -0700103 // Random variation in backup scheduling time to avoid server load spikes
104 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
105
Christopher Tate8031a3d2009-07-06 16:36:05 -0700106 // The amount of time between the initial provisioning of the device and
107 // the first backup pass.
108 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
109
Christopher Tate45281862010-03-05 15:46:30 -0800110 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
111 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
112 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700113 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700114 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700115 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700116 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700117 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700118 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
119 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800120 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700121 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
122 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700123
124 // Timeout interval for deciding that a bind or clear-data has taken too long
125 static final long TIMEOUT_INTERVAL = 10 * 1000;
126
Christopher Tate44a27902010-01-27 17:15:49 -0800127 // Timeout intervals for agent backup & restore operations
128 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700129 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800130 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
131
Christopher Tate4a627c72011-04-01 14:43:32 -0700132 // User confirmation timeout for a full backup/restore operation
133 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
134
Christopher Tate487529a2009-04-29 14:03:25 -0700135 private Context mContext;
136 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700138 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700139 private PowerManager mPowerManager;
140 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800141 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700142
Christopher Tate73e02522009-07-15 14:18:26 -0700143 boolean mEnabled; // access to this is synchronized on 'this'
144 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800145 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700146 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800147 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
148 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700149 PendingIntent mRunBackupIntent, mRunInitIntent;
150 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700151 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700152 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700153 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700154 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700155 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700156 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700157
Christopher Tate4a627c72011-04-01 14:43:32 -0700158 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700159 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700160 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700161
162 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700163 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700164 }
Christopher Tate46758122009-05-06 11:22:00 -0700165 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800166 // Backups that we haven't started yet. Keys are package names.
167 HashMap<String,BackupRequest> mPendingBackups
168 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700169
170 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700171 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700172
173 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700174 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700175
Christopher Tate043dadc2009-06-02 16:11:00 -0700176 // The thread performing the sequence of queued backups binds to each app's agent
177 // in succession. Bind notifications are asynchronously delivered through the
178 // Activity Manager; use this lock object to signal when a requested binding has
179 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700180 final Object mAgentConnectLock = new Object();
181 IBackupAgent mConnectedAgent;
182 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700183 volatile long mLastBackupPass;
184 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700185
Christopher Tate55f931a2009-09-29 17:17:34 -0700186 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700187 final Object mClearDataLock = new Object();
188 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700189
Christopher Tate91717492009-06-26 21:07:13 -0700190 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700191 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700192 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700193 String mCurrentTransport;
194 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800195 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700196
Christopher Tate2d449afe2010-03-29 19:14:24 -0700197 class RestoreGetSetsParams {
198 public IBackupTransport transport;
199 public ActiveRestoreSession session;
200 public IRestoreObserver observer;
201
202 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
203 IRestoreObserver _observer) {
204 transport = _transport;
205 session = _session;
206 observer = _observer;
207 }
208 }
209
Christopher Tate73e02522009-07-15 14:18:26 -0700210 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700211 public IBackupTransport transport;
212 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700213 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800214 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800215 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700216 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800217
218 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700219 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800220 transport = _transport;
221 observer = _obs;
222 token = _token;
223 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800224 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700225 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800226 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700227
Chris Tate249345b2010-10-29 12:57:04 -0700228 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
229 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700230 transport = _transport;
231 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700232 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800233 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800234 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700235 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700236 }
237 }
238
Christopher Tate73e02522009-07-15 14:18:26 -0700239 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700240 public IBackupTransport transport;
241 public PackageInfo packageInfo;
242
243 ClearParams(IBackupTransport _transport, PackageInfo _info) {
244 transport = _transport;
245 packageInfo = _info;
246 }
247 }
248
Christopher Tate4a627c72011-04-01 14:43:32 -0700249 class FullParams {
250 public ParcelFileDescriptor fd;
251 public final AtomicBoolean latch;
252 public IFullBackupRestoreObserver observer;
253
254 FullParams() {
255 latch = new AtomicBoolean(false);
256 }
257 }
258
259 class FullBackupParams extends FullParams {
260 public boolean includeApks;
261 public boolean includeShared;
262 public boolean allApps;
263 public String[] packages;
264
265 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
266 boolean doAllApps, String[] pkgList) {
267 fd = output;
268 includeApks = saveApks;
269 includeShared = saveShared;
270 allApps = doAllApps;
271 packages = pkgList;
272 }
273 }
274
275 class FullRestoreParams extends FullParams {
276 FullRestoreParams(ParcelFileDescriptor input) {
277 fd = input;
278 }
279 }
280
Christopher Tate44a27902010-01-27 17:15:49 -0800281 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
282 // token is the index of the entry in the pending-operations list.
283 static final int OP_PENDING = 0;
284 static final int OP_ACKNOWLEDGED = 1;
285 static final int OP_TIMEOUT = -1;
286
287 final SparseIntArray mCurrentOperations = new SparseIntArray();
288 final Object mCurrentOpLock = new Object();
289 final Random mTokenGenerator = new Random();
290
Christopher Tate4a627c72011-04-01 14:43:32 -0700291 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
292
Christopher Tate5cb400b2009-06-25 16:03:14 -0700293 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700294 File mBaseStateDir;
295 File mDataDir;
296 File mJournalDir;
297 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700298
Christopher Tate84725812010-02-04 15:52:40 -0800299 // Keep a log of all the apps we've ever backed up, and what the
300 // dataset tokens are for both the current backup dataset and
301 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700302 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700303 HashSet<String> mEverStoredApps = new HashSet<String>();
304
Christopher Tateb49ceb32010-02-08 16:22:24 -0800305 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800306 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800307 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800308 long mAncestralToken = 0;
309 long mCurrentToken = 0;
310
Christopher Tate4cc86e12009-09-21 19:36:51 -0700311 // Persistently track the need to do a full init
312 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
313 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700314
Christopher Tate4a627c72011-04-01 14:43:32 -0700315 // Utility: build a new random integer token
316 int generateToken() {
317 int token;
318 do {
319 synchronized (mTokenGenerator) {
320 token = mTokenGenerator.nextInt();
321 }
322 } while (token < 0);
323 return token;
324 }
325
Christopher Tate44a27902010-01-27 17:15:49 -0800326 // ----- Asynchronous backup/restore handler thread -----
327
328 private class BackupHandler extends Handler {
329 public BackupHandler(Looper looper) {
330 super(looper);
331 }
332
333 public void handleMessage(Message msg) {
334
335 switch (msg.what) {
336 case MSG_RUN_BACKUP:
337 {
338 mLastBackupPass = System.currentTimeMillis();
339 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
340
341 IBackupTransport transport = getTransport(mCurrentTransport);
342 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800343 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800344 mWakelock.release();
345 break;
346 }
347
348 // snapshot the pending-backup set and work on that
349 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800350 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800351 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800352 // Do we have any work to do? Construct the work queue
353 // then release the synchronization lock to actually run
354 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800355 if (mPendingBackups.size() > 0) {
356 for (BackupRequest b: mPendingBackups.values()) {
357 queue.add(b);
358 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800359 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800360 mPendingBackups.clear();
361
362 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800363 mJournal = null;
364
Christopher Tate44a27902010-01-27 17:15:49 -0800365 }
366 }
Christopher Tatec61da312010-02-05 10:41:27 -0800367
368 if (queue.size() > 0) {
369 // At this point, we have started a new journal file, and the old
370 // file identity is being passed to the backup processing thread.
371 // When it completes successfully, that old journal file will be
372 // deleted. If we crash prior to that, the old journal is parsed
373 // at next boot and the journaled requests fulfilled.
374 (new PerformBackupTask(transport, queue, oldJournal)).run();
375 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800376 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800377 mWakelock.release();
378 }
Christopher Tate44a27902010-01-27 17:15:49 -0800379 break;
380 }
381
382 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700383 {
384 FullBackupParams params = (FullBackupParams)msg.obj;
385 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
386 params.includeShared, params.allApps, params.packages,
387 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800388 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700389 }
Christopher Tate44a27902010-01-27 17:15:49 -0800390
391 case MSG_RUN_RESTORE:
392 {
393 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800394 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800395 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700396 params.token, params.pkgInfo, params.pmToken,
397 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800398 break;
399 }
400
401 case MSG_RUN_CLEAR:
402 {
403 ClearParams params = (ClearParams)msg.obj;
404 (new PerformClearTask(params.transport, params.packageInfo)).run();
405 break;
406 }
407
408 case MSG_RUN_INITIALIZE:
409 {
410 HashSet<String> queue;
411
412 // Snapshot the pending-init queue and work on that
413 synchronized (mQueueLock) {
414 queue = new HashSet<String>(mPendingInits);
415 mPendingInits.clear();
416 }
417
418 (new PerformInitializeTask(queue)).run();
419 break;
420 }
421
Christopher Tate2d449afe2010-03-29 19:14:24 -0700422 case MSG_RUN_GET_RESTORE_SETS:
423 {
424 // Like other async operations, this is entered with the wakelock held
425 RestoreSet[] sets = null;
426 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
427 try {
428 sets = params.transport.getAvailableRestoreSets();
429 // cache the result in the active session
430 synchronized (params.session) {
431 params.session.mRestoreSets = sets;
432 }
433 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
434 } catch (Exception e) {
435 Slog.e(TAG, "Error from transport getting set list");
436 } finally {
437 if (params.observer != null) {
438 try {
439 params.observer.restoreSetsAvailable(sets);
440 } catch (RemoteException re) {
441 Slog.e(TAG, "Unable to report listing to observer");
442 } catch (Exception e) {
443 Slog.e(TAG, "Restore observer threw", e);
444 }
445 }
446
Christopher Tate2a935092011-03-03 17:30:32 -0800447 // Done: reset the session timeout clock
448 removeMessages(MSG_RESTORE_TIMEOUT);
449 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
450
Christopher Tate2d449afe2010-03-29 19:14:24 -0700451 mWakelock.release();
452 }
453 break;
454 }
455
Christopher Tate44a27902010-01-27 17:15:49 -0800456 case MSG_TIMEOUT:
457 {
458 synchronized (mCurrentOpLock) {
459 final int token = msg.arg1;
460 int state = mCurrentOperations.get(token, OP_TIMEOUT);
461 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800462 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800463 mCurrentOperations.put(token, OP_TIMEOUT);
464 }
465 mCurrentOpLock.notifyAll();
466 }
467 break;
468 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800469
470 case MSG_RESTORE_TIMEOUT:
471 {
472 synchronized (BackupManagerService.this) {
473 if (mActiveRestoreSession != null) {
474 // Client app left the restore session dangling. We know that it
475 // can't be in the middle of an actual restore operation because
476 // those are executed serially on this same handler thread. Clean
477 // up now.
478 Slog.w(TAG, "Restore session timed out; aborting");
479 post(mActiveRestoreSession.new EndRestoreRunnable(
480 BackupManagerService.this, mActiveRestoreSession));
481 }
482 }
483 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700484
485 case MSG_FULL_CONFIRMATION_TIMEOUT:
486 {
487 synchronized (mFullConfirmations) {
488 FullParams params = mFullConfirmations.get(msg.arg1);
489 if (params != null) {
490 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
491
492 // Release the waiter; timeout == completion
493 signalFullBackupRestoreCompletion(params);
494
495 // Remove the token from the set
496 mFullConfirmations.delete(msg.arg1);
497
498 // Report a timeout to the observer, if any
499 if (params.observer != null) {
500 try {
501 params.observer.onTimeout();
502 } catch (RemoteException e) {
503 /* don't care if the app has gone away */
504 }
505 }
506 } else {
507 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
508 }
509 }
510 break;
511 }
Christopher Tate44a27902010-01-27 17:15:49 -0800512 }
513 }
514 }
515
516 // ----- Main service implementation -----
517
Christopher Tate487529a2009-04-29 14:03:25 -0700518 public BackupManagerService(Context context) {
519 mContext = context;
520 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700521 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700522 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700523
Christopher Tateb6787f22009-07-02 17:40:45 -0700524 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
525 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
526
Christopher Tate44a27902010-01-27 17:15:49 -0800527 mBackupManagerBinder = asInterface(asBinder());
528
529 // spin up the backup/restore handler thread
530 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
531 mHandlerThread.start();
532 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
533
Christopher Tate22b87872009-05-04 16:41:53 -0700534 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700535 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700536 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700537 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700538 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800539 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800540 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800541 // If Encrypted file systems is enabled or disabled, this call will return the
542 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600543 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800544 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700545 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700546
Christopher Tate4cc86e12009-09-21 19:36:51 -0700547 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700548 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700549 IntentFilter filter = new IntentFilter();
550 filter.addAction(RUN_BACKUP_ACTION);
551 context.registerReceiver(mRunBackupReceiver, filter,
552 android.Manifest.permission.BACKUP, null);
553
554 mRunInitReceiver = new RunInitializeReceiver();
555 filter = new IntentFilter();
556 filter.addAction(RUN_INITIALIZE_ACTION);
557 context.registerReceiver(mRunInitReceiver, filter,
558 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700559
560 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700561 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
562 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
563
Christopher Tate4cc86e12009-09-21 19:36:51 -0700564 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
565 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
566 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
567
Christopher Tatecde87f42009-06-12 12:55:53 -0700568 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700569 mJournalDir = new File(mBaseStateDir, "pending");
570 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700571 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700572
Christopher Tate73e02522009-07-15 14:18:26 -0700573 // Set up the various sorts of package tracking we do
574 initPackageTracking();
575
Christopher Tateabce4e82009-06-18 18:35:32 -0700576 // Build our mapping of uid to backup client services. This implicitly
577 // schedules a backup pass on the Package Manager metadata the first
578 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700579 synchronized (mBackupParticipants) {
580 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700581 }
582
Dan Egnor87a02bc2009-06-17 02:30:10 -0700583 // Set up our transport options and initialize the default transport
584 // TODO: Have transports register themselves somehow?
585 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700586 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700587 ComponentName localName = new ComponentName(context, LocalTransport.class);
588 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700589
Christopher Tate91717492009-06-26 21:07:13 -0700590 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700591 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
592 Settings.Secure.BACKUP_TRANSPORT);
593 if ("".equals(mCurrentTransport)) {
594 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700595 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800596 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700597
598 // Attach to the Google backup transport. When this comes up, it will set
599 // itself as the current transport because we explicitly reset mCurrentTransport
600 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700601 ComponentName transportComponent = new ComponentName("com.google.android.backup",
602 "com.google.android.backup.BackupTransportService");
603 try {
604 // If there's something out there that is supposed to be the Google
605 // backup transport, make sure it's legitimately part of the OS build
606 // and not an app lying about its package name.
607 ApplicationInfo info = mPackageManager.getApplicationInfo(
608 transportComponent.getPackageName(), 0);
609 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
610 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
611 Intent intent = new Intent().setComponent(transportComponent);
612 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
613 } else {
614 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
615 }
616 } catch (PackageManager.NameNotFoundException nnf) {
617 // No such package? No binding.
618 if (DEBUG) Slog.v(TAG, "Google transport not present");
619 }
Christopher Tateaa088442009-06-16 18:25:46 -0700620
Christopher Tatecde87f42009-06-12 12:55:53 -0700621 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700622 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700623 parseLeftoverJournals();
624
Christopher Tateb6787f22009-07-02 17:40:45 -0700625 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700626 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700627
628 // Start the backup passes going
629 setBackupEnabled(areEnabled);
630 }
631
632 private class RunBackupReceiver extends BroadcastReceiver {
633 public void onReceive(Context context, Intent intent) {
634 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700635 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700636 if (mPendingInits.size() > 0) {
637 // If there are pending init operations, we process those
638 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800639 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700640 try {
641 mAlarmManager.cancel(mRunInitIntent);
642 mRunInitIntent.send();
643 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800644 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700645 // can't really do more than bail here
646 }
647 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800648 // Don't run backups now if we're disabled or not yet
649 // fully set up.
650 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800651 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700652
653 // Acquire the wakelock and pass it to the backup thread. it will
654 // be released once backup concludes.
655 mWakelock.acquire();
656
657 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
658 mBackupHandler.sendMessage(msg);
659 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800660 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700661 }
662 }
663 }
664 }
665 }
666 }
667
668 private class RunInitializeReceiver extends BroadcastReceiver {
669 public void onReceive(Context context, Intent intent) {
670 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
671 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800672 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700673
674 // Acquire the wakelock and pass it to the init thread. it will
675 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700676 mWakelock.acquire();
677
Christopher Tate4cc86e12009-09-21 19:36:51 -0700678 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700679 mBackupHandler.sendMessage(msg);
680 }
681 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700682 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700683 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700684
Christopher Tate73e02522009-07-15 14:18:26 -0700685 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800686 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700687
Christopher Tate84725812010-02-04 15:52:40 -0800688 // Remember our ancestral dataset
689 mTokenFile = new File(mBaseStateDir, "ancestral");
690 try {
691 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800692 int version = tf.readInt();
693 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
694 mAncestralToken = tf.readLong();
695 mCurrentToken = tf.readLong();
696
697 int numPackages = tf.readInt();
698 if (numPackages >= 0) {
699 mAncestralPackages = new HashSet<String>();
700 for (int i = 0; i < numPackages; i++) {
701 String pkgName = tf.readUTF();
702 mAncestralPackages.add(pkgName);
703 }
704 }
705 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800706 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800707 } catch (FileNotFoundException fnf) {
708 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800709 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800710 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800711 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800712 }
713
Christopher Tatee97e8072009-07-15 16:45:50 -0700714 // Keep a log of what apps we've ever backed up. Because we might have
715 // rebooted in the middle of an operation that was removing something from
716 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700717 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700718 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700719
Christopher Tatee97e8072009-07-15 16:45:50 -0700720 // If we were in the middle of removing something from the ever-backed-up
721 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700722 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700723 if (tempProcessedFile.exists()) {
724 tempProcessedFile.delete();
725 }
726
Dan Egnor852f8e42009-09-30 11:20:45 -0700727 // If there are previous contents, parse them out then start a new
728 // file to continue the recordkeeping.
729 if (mEverStored.exists()) {
730 RandomAccessFile temp = null;
731 RandomAccessFile in = null;
732
733 try {
734 temp = new RandomAccessFile(tempProcessedFile, "rws");
735 in = new RandomAccessFile(mEverStored, "r");
736
737 while (true) {
738 PackageInfo info;
739 String pkg = in.readUTF();
740 try {
741 info = mPackageManager.getPackageInfo(pkg, 0);
742 mEverStoredApps.add(pkg);
743 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800744 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700745 } catch (NameNotFoundException e) {
746 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800747 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700748 }
749 }
750 } catch (EOFException e) {
751 // Once we've rewritten the backup history log, atomically replace the
752 // old one with the new one then reopen the file for continuing use.
753 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800754 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700755 }
756 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800757 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700758 } finally {
759 try { if (temp != null) temp.close(); } catch (IOException e) {}
760 try { if (in != null) in.close(); } catch (IOException e) {}
761 }
762 }
763
Christopher Tate73e02522009-07-15 14:18:26 -0700764 // Register for broadcasts about package install, etc., so we can
765 // update the provider list.
766 IntentFilter filter = new IntentFilter();
767 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
768 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
769 filter.addDataScheme("package");
770 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800771 // Register for events related to sdcard installation.
772 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800773 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
774 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800775 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700776 }
777
Christopher Tatecde87f42009-06-12 12:55:53 -0700778 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700779 for (File f : mJournalDir.listFiles()) {
780 if (mJournal == null || f.compareTo(mJournal) != 0) {
781 // This isn't the current journal, so it must be a leftover. Read
782 // out the package names mentioned there and schedule them for
783 // backup.
784 RandomAccessFile in = null;
785 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400786 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700787 in = new RandomAccessFile(f, "r");
788 while (true) {
789 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400790 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700791 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700792 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700793 } catch (EOFException e) {
794 // no more data; we're done
795 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800796 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700797 } finally {
798 // close/delete the file
799 try { if (in != null) in.close(); } catch (IOException e) {}
800 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700801 }
802 }
803 }
804 }
805
Christopher Tate4cc86e12009-09-21 19:36:51 -0700806 // Maintain persistent state around whether need to do an initialize operation.
807 // Must be called with the queue lock held.
808 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800809 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700810 + " on transport " + transportName);
811 try {
812 IBackupTransport transport = getTransport(transportName);
813 String transportDirName = transport.transportDirName();
814 File stateDir = new File(mBaseStateDir, transportDirName);
815 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
816
817 if (isPending) {
818 // We need an init before we can proceed with sending backup data.
819 // Record that with an entry in our set of pending inits, as well as
820 // journaling it via creation of a sentinel file.
821 mPendingInits.add(transportName);
822 try {
823 (new FileOutputStream(initPendingFile)).close();
824 } catch (IOException ioe) {
825 // Something is badly wrong with our permissions; just try to move on
826 }
827 } else {
828 // No more initialization needed; wipe the journal and reset our state.
829 initPendingFile.delete();
830 mPendingInits.remove(transportName);
831 }
832 } catch (RemoteException e) {
833 // can't happen; the transport is local
834 }
835 }
836
Christopher Tated55e18a2009-09-21 10:12:59 -0700837 // Reset all of our bookkeeping, in response to having been told that
838 // the backend data has been wiped [due to idle expiry, for example],
839 // so we must re-upload all saved settings.
840 void resetBackupState(File stateFileDir) {
841 synchronized (mQueueLock) {
842 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700843 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700844 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700845
Christopher Tate84725812010-02-04 15:52:40 -0800846 mCurrentToken = 0;
847 writeRestoreTokens();
848
Christopher Tated55e18a2009-09-21 10:12:59 -0700849 // Remove all the state files
850 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700851 // ... but don't touch the needs-init sentinel
852 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
853 sf.delete();
854 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700855 }
Christopher Tate45597642011-04-04 16:59:21 -0700856 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700857
Christopher Tate45597642011-04-04 16:59:21 -0700858 // Enqueue a new backup of every participant
859 int N = mBackupParticipants.size();
860 for (int i=0; i<N; i++) {
861 int uid = mBackupParticipants.keyAt(i);
862 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
863 for (ApplicationInfo app: participants) {
864 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700865 }
866 }
867 }
868
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800869 // Add a transport to our set of available backends. If 'transport' is null, this
870 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700871 private void registerTransport(String name, IBackupTransport transport) {
872 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800873 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800874 if (transport != null) {
875 mTransports.put(name, transport);
876 } else {
877 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800878 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800879 mCurrentTransport = null;
880 }
881 // Nothing further to do in the unregistration case
882 return;
883 }
Christopher Tate91717492009-06-26 21:07:13 -0700884 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700885
886 // If the init sentinel file exists, we need to be sure to perform the init
887 // as soon as practical. We also create the state directory at registration
888 // time to ensure it's present from the outset.
889 try {
890 String transportName = transport.transportDirName();
891 File stateDir = new File(mBaseStateDir, transportName);
892 stateDir.mkdirs();
893
894 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
895 if (initSentinel.exists()) {
896 synchronized (mQueueLock) {
897 mPendingInits.add(transportName);
898
899 // TODO: pick a better starting time than now + 1 minute
900 long delay = 1000 * 60; // one minute, in milliseconds
901 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
902 System.currentTimeMillis() + delay, mRunInitIntent);
903 }
904 }
905 } catch (RemoteException e) {
906 // can't happen, the transport is local
907 }
Christopher Tate91717492009-06-26 21:07:13 -0700908 }
909
Christopher Tate3799bc22009-05-06 16:13:56 -0700910 // ----- Track installation/removal of packages -----
911 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
912 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800913 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700914
Christopher Tate3799bc22009-05-06 16:13:56 -0700915 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800916 boolean replacing = false;
917 boolean added = false;
918 Bundle extras = intent.getExtras();
919 String pkgList[] = null;
920 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
921 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
922 Uri uri = intent.getData();
923 if (uri == null) {
924 return;
925 }
926 String pkgName = uri.getSchemeSpecificPart();
927 if (pkgName != null) {
928 pkgList = new String[] { pkgName };
929 }
930 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
931 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800932 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800933 added = true;
934 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800935 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800936 added = false;
937 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
938 }
939 if (pkgList == null || pkgList.length == 0) {
940 return;
941 }
942 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700943 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800944 for (String pkgName : pkgList) {
945 if (replacing) {
946 // The package was just upgraded
947 updatePackageParticipantsLocked(pkgName);
948 } else {
949 // The package was just added
950 addPackageParticipantsLocked(pkgName);
951 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700952 }
953 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800954 } else {
955 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700956 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
957 } else {
958 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800959 for (String pkgName : pkgList) {
960 removePackageParticipantsLocked(pkgName);
961 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700962 }
963 }
964 }
965 }
966 };
967
Dan Egnor87a02bc2009-06-17 02:30:10 -0700968 // ----- Track connection to GoogleBackupTransport service -----
969 ServiceConnection mGoogleConnection = new ServiceConnection() {
970 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800971 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700972 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700973 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700974 }
975
976 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800977 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700978 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700979 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700980 }
981 };
982
Christopher Tate181fafa2009-05-14 11:12:14 -0700983 // Add the backup agents in the given package to our set of known backup participants.
984 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700985 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700986 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800987 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700988 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700989 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700990 }
991
Christopher Tate181fafa2009-05-14 11:12:14 -0700992 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700993 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700994 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800995 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700996 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700998 + " uid=" + p.applicationInfo.uid
999 + " killAfterRestore="
1000 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001001 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001002 }
1003 }
1004
Dan Egnorefe52642009-06-24 00:16:33 -07001005 for (PackageInfo pkg : targetPkgs) {
1006 if (packageName == null || pkg.packageName.equals(packageName)) {
1007 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001008 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001009 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001010 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001011 mBackupParticipants.put(uid, set);
1012 }
Dan Egnorefe52642009-06-24 00:16:33 -07001013 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001014
1015 // If we've never seen this app before, schedule a backup for it
1016 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001017 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001018 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001019 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001020 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001021 }
Christopher Tate487529a2009-04-29 14:03:25 -07001022 }
1023 }
1024
Christopher Tate6785dd82009-06-18 15:58:25 -07001025 // Remove the given package's entry from our known active set. If
1026 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001027 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001029 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001030 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001031 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 } else {
1033 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001034 List<PackageInfo> knownPackages = allAgentPackages();
1035 for (PackageInfo pkg : knownPackages) {
1036 allApps.add(pkg.packageName);
1037 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001038 }
1039 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001040 }
1041
Joe Onorato8ad02812009-05-13 01:41:44 -04001042 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001043 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001044 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001045 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001046 + ") removing " + allPackageNames.size() + " entries");
1047 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001048 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001049 }
1050 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001051 for (String pkg : allPackageNames) {
1052 if (packageName == null || pkg.equals(packageName)) {
1053 int uid = -1;
1054 try {
1055 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1056 uid = info.applicationInfo.uid;
1057 } catch (NameNotFoundException e) {
1058 // we don't know this package name, so just skip it for now
1059 continue;
1060 }
1061
Christopher Tate181fafa2009-05-14 11:12:14 -07001062 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001063 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001064 // Find the existing entry with the same package name, and remove it.
1065 // We can't just remove(app) because the instances are different.
1066 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001067 if (entry.packageName.equals(pkg)) {
1068 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001069 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001070 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001071 break;
1072 }
1073 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001074 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001075 mBackupParticipants.delete(uid);
1076 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001077 }
1078 }
1079 }
1080 }
1081
Christopher Tate181fafa2009-05-14 11:12:14 -07001082 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001083 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001084 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001085 int flags = PackageManager.GET_SIGNATURES;
1086 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1087 int N = packages.size();
1088 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001089 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001090 try {
1091 ApplicationInfo app = pkg.applicationInfo;
1092 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001093 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001094 packages.remove(a);
1095 }
1096 else {
1097 // we will need the shared library path, so look that up and store it here
1098 app = mPackageManager.getApplicationInfo(pkg.packageName,
1099 PackageManager.GET_SHARED_LIBRARY_FILES);
1100 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1101 }
1102 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001103 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001104 }
1105 }
Dan Egnorefe52642009-06-24 00:16:33 -07001106 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001107 }
Christopher Tateaa088442009-06-16 18:25:46 -07001108
Christopher Tate3799bc22009-05-06 16:13:56 -07001109 // Reset the given package's known backup participants. Unlike add/remove, the update
1110 // action cannot be passed a null package name.
1111 void updatePackageParticipantsLocked(String packageName) {
1112 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001113 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001114 return;
1115 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001116 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001117
1118 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001119 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001120 List<String> allAppNames = new ArrayList<String>();
1121 for (PackageInfo pkg : allApps) {
1122 allAppNames.add(pkg.packageName);
1123 }
1124 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001125 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001126 }
1127
Christopher Tate84725812010-02-04 15:52:40 -08001128 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001129 // backed up at least once
1130 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001131 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1132
1133 synchronized (mEverStoredApps) {
1134 if (!mEverStoredApps.add(packageName)) return;
1135
1136 RandomAccessFile out = null;
1137 try {
1138 out = new RandomAccessFile(mEverStored, "rws");
1139 out.seek(out.length());
1140 out.writeUTF(packageName);
1141 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001142 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001143 } finally {
1144 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001145 }
1146 }
1147 }
1148
Christopher Tatee97e8072009-07-15 16:45:50 -07001149 // Remove our awareness of having ever backed up the given package
1150 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001151 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001152
Dan Egnor852f8e42009-09-30 11:20:45 -07001153 synchronized (mEverStoredApps) {
1154 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1155 // we'll recognize on initialization time that the package no longer
1156 // exists and fix it up then.
1157 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1158 RandomAccessFile known = null;
1159 try {
1160 known = new RandomAccessFile(tempKnownFile, "rws");
1161 mEverStoredApps.remove(packageName);
1162 for (String s : mEverStoredApps) {
1163 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001164 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001165 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001166 known.close();
1167 known = null;
1168 if (!tempKnownFile.renameTo(mEverStored)) {
1169 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1170 }
1171 } catch (IOException e) {
1172 // Bad: we couldn't create the new copy. For safety's sake we
1173 // abandon the whole process and remove all what's-backed-up
1174 // state entirely, meaning we'll force a backup pass for every
1175 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001176 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001177 mEverStoredApps.clear();
1178 tempKnownFile.delete();
1179 mEverStored.delete();
1180 } finally {
1181 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001182 }
1183 }
1184 }
1185
Christopher Tateb49ceb32010-02-08 16:22:24 -08001186 // Persistently record the current and ancestral backup tokens as well
1187 // as the set of packages with data [supposedly] available in the
1188 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001189 void writeRestoreTokens() {
1190 try {
1191 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001192
1193 // First, the version number of this record, for futureproofing
1194 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1195
1196 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001197 af.writeLong(mAncestralToken);
1198 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001199
1200 // Now write the set of ancestral packages
1201 if (mAncestralPackages == null) {
1202 af.writeInt(-1);
1203 } else {
1204 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001205 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001206 for (String pkgName : mAncestralPackages) {
1207 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001208 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001209 }
1210 }
Christopher Tate84725812010-02-04 15:52:40 -08001211 af.close();
1212 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001213 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001214 }
1215 }
1216
Dan Egnor87a02bc2009-06-17 02:30:10 -07001217 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001218 private IBackupTransport getTransport(String transportName) {
1219 synchronized (mTransports) {
1220 IBackupTransport transport = mTransports.get(transportName);
1221 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001222 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001223 }
1224 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001225 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001226 }
1227
Christopher Tatedf01dea2009-06-09 20:45:02 -07001228 // fire off a backup agent, blocking until it attaches or times out
1229 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1230 IBackupAgent agent = null;
1231 synchronized(mAgentConnectLock) {
1232 mConnecting = true;
1233 mConnectedAgent = null;
1234 try {
1235 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001237
1238 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001239 // only wait 10 seconds for the clear data to happen
1240 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1241 while (mConnecting && mConnectedAgent == null
1242 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001243 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001244 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001245 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001246 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001247 return null;
1248 }
1249 }
1250
1251 // if we timed out with no connect, abort and move on
1252 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001253 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001254 return null;
1255 }
1256 agent = mConnectedAgent;
1257 }
1258 } catch (RemoteException e) {
1259 // can't happen
1260 }
1261 }
1262 return agent;
1263 }
1264
Christopher Tatec7b31e32009-06-10 15:49:30 -07001265 // clear an application's data, blocking until the operation completes or times out
1266 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001267 // Don't wipe packages marked allowClearUserData=false
1268 try {
1269 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1270 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001271 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001272 + packageName);
1273 return;
1274 }
1275 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001276 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001277 return;
1278 }
1279
Christopher Tatec7b31e32009-06-10 15:49:30 -07001280 ClearDataObserver observer = new ClearDataObserver();
1281
1282 synchronized(mClearDataLock) {
1283 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001284 try {
1285 mActivityManager.clearApplicationUserData(packageName, observer);
1286 } catch (RemoteException e) {
1287 // can't happen because the activity manager is in this process
1288 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001289
1290 // only wait 10 seconds for the clear data to happen
1291 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1292 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1293 try {
1294 mClearDataLock.wait(5000);
1295 } catch (InterruptedException e) {
1296 // won't happen, but still.
1297 mClearingData = false;
1298 }
1299 }
1300 }
1301 }
1302
1303 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001304 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001305 synchronized(mClearDataLock) {
1306 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001307 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001308 }
1309 }
1310 }
1311
Christopher Tate1bb69062010-02-19 17:02:12 -08001312 // Get the restore-set token for the best-available restore set for this package:
1313 // the active set if possible, else the ancestral one. Returns zero if none available.
1314 long getAvailableRestoreToken(String packageName) {
1315 long token = mAncestralToken;
1316 synchronized (mQueueLock) {
1317 if (mEverStoredApps.contains(packageName)) {
1318 token = mCurrentToken;
1319 }
1320 }
1321 return token;
1322 }
1323
Christopher Tate44a27902010-01-27 17:15:49 -08001324 // -----
1325 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1326 boolean waitUntilOperationComplete(int token) {
1327 int finalState = OP_PENDING;
1328 synchronized (mCurrentOpLock) {
1329 try {
1330 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1331 try {
1332 mCurrentOpLock.wait();
1333 } catch (InterruptedException e) {}
1334 }
1335 } catch (IndexOutOfBoundsException e) {
1336 // the operation has been mysteriously cleared from our
1337 // bookkeeping -- consider this a success and ignore it.
1338 }
1339 }
1340 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001341 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001342 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001343 return finalState == OP_ACKNOWLEDGED;
1344 }
1345
1346 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001347 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001348 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001349 synchronized (mCurrentOpLock) {
1350 mCurrentOperations.put(token, OP_PENDING);
1351 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1352 mBackupHandler.sendMessageDelayed(msg, interval);
1353 }
Christopher Tate44a27902010-01-27 17:15:49 -08001354 }
1355
Christopher Tate043dadc2009-06-02 16:11:00 -07001356 // ----- Back up a set of applications via a worker thread -----
1357
Christopher Tate44a27902010-01-27 17:15:49 -08001358 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001359 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001360 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001361 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001362 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001363 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001364
Christopher Tate44a27902010-01-27 17:15:49 -08001365 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001366 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001367 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001368 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001369 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001370
1371 try {
1372 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1373 } catch (RemoteException e) {
1374 // can't happen; the transport is local
1375 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001376 }
1377
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001379 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001380 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001382
Christopher Tate79588342009-06-30 16:11:49 -07001383 // Backups run at background priority
1384 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1385
Christopher Tate043dadc2009-06-02 16:11:00 -07001386 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001387 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001388
Dan Egnor852f8e42009-09-30 11:20:45 -07001389 // If we haven't stored package manager metadata yet, we must init the transport.
1390 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1391 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001392 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001393 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001394 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001395 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001396 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001397 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001398 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001399 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001400 }
Dan Egnor01445162009-09-21 17:04:05 -07001401 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001402
1403 // The package manager doesn't have a proper <application> etc, but since
1404 // it's running here in the system process we can just set up its agent
1405 // directly and use a synthetic BackupRequest. We always run this pass
1406 // because it's cheap and this way we guarantee that we don't get out of
1407 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001408 if (status == BackupConstants.TRANSPORT_OK) {
1409 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1410 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001411 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001412 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1413 status = processOneBackup(pmRequest,
1414 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1415 }
Christopher Tate90967f42009-09-20 15:28:33 -07001416
Dan Egnor01445162009-09-21 17:04:05 -07001417 if (status == BackupConstants.TRANSPORT_OK) {
1418 // Now run all the backups in our queue
1419 status = doQueuedBackups(mTransport);
1420 }
1421
1422 if (status == BackupConstants.TRANSPORT_OK) {
1423 // Tell the transport to finish everything it has buffered
1424 status = mTransport.finishBackup();
1425 if (status == BackupConstants.TRANSPORT_OK) {
1426 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001427 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001428 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001430 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001431 }
1432 }
1433
Dan Egnor01445162009-09-21 17:04:05 -07001434 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001435 // The backend reports that our dataset has been wiped. We need to
1436 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001437 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001438 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001439 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 }
1441 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001442 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001443 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001444 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001445 // If everything actually went through and this is the first time we've
1446 // done a backup, we can now record what the current backup dataset token
1447 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001448 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001449 try {
1450 mCurrentToken = mTransport.getCurrentRestoreSet();
1451 } catch (RemoteException e) { /* cannot happen */ }
1452 writeRestoreTokens();
1453 }
1454
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001455 // If things went wrong, we need to re-stage the apps we had expected
1456 // to be backing up in this pass. This journals the package names in
1457 // the current active pending-backup file, not in the we are holding
1458 // here in mJournal.
1459 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001460 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001461 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001462 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001463 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001464
1465 // We also want to reset the backup schedule based on whatever
1466 // the transport suggests by way of retry/backoff time.
1467 try {
1468 startBackupAlarmsLocked(mTransport.requestBackupTime());
1469 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001470 }
1471
1472 // Either backup was successful, in which case we of course do not need
1473 // this pass's journal any more; or it failed, in which case we just
1474 // re-enqueued all of these packages in the current active journal.
1475 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001476 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001478 }
1479
Christopher Tatec2af5d32010-02-02 15:18:58 -08001480 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001481 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001482 backupNow();
1483 }
1484
Dan Egnorbb9001c2009-07-27 12:20:13 -07001485 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001486 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001487 }
1488
Dan Egnor01445162009-09-21 17:04:05 -07001489 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001490 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001492
Christopher Tatec28083a2010-12-14 16:16:44 -08001493 // Verify that the requested app exists; it might be something that
1494 // requested a backup but was then uninstalled. The request was
1495 // journalled and rather than tamper with the journal it's safer
1496 // to sanity-check here.
1497 try {
1498 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1499 } catch (NameNotFoundException e) {
1500 Slog.d(TAG, "Package does not exist; skipping");
1501 continue;
1502 }
1503
Christopher Tate043dadc2009-06-02 16:11:00 -07001504 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001505 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001506 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001507 agent = bindToAgentSynchronous(request.appInfo,
1508 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001509 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001510 int result = processOneBackup(request, agent, transport);
1511 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001512 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001513 } catch (SecurityException ex) {
1514 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001516 } finally {
1517 try { // unbind even on timeout, just in case
1518 mActivityManager.unbindBackupAgent(request.appInfo);
1519 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001520 }
1521 }
Dan Egnor01445162009-09-21 17:04:05 -07001522
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001523 mWakelock.setWorkSource(null);
1524
Dan Egnor01445162009-09-21 17:04:05 -07001525 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001526 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001527
Dan Egnor01445162009-09-21 17:04:05 -07001528 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1529 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001530 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001531 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001532
Dan Egnorbb9001c2009-07-27 12:20:13 -07001533 File savedStateName = new File(mStateDir, packageName);
1534 File backupDataName = new File(mDataDir, packageName + ".data");
1535 File newStateName = new File(mStateDir, packageName + ".new");
1536
1537 ParcelFileDescriptor savedState = null;
1538 ParcelFileDescriptor backupData = null;
1539 ParcelFileDescriptor newState = null;
1540
1541 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001542 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001543 try {
1544 // Look up the package info & signatures. This is first so that if it
1545 // throws an exception, there's no file setup yet that would need to
1546 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001547 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1548 // The metadata 'package' is synthetic
1549 packInfo = new PackageInfo();
1550 packInfo.packageName = packageName;
1551 } else {
1552 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001553 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001554 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555
Christopher Tatec7b31e32009-06-10 15:49:30 -07001556 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001557 // the saved-state "file". This is by definition an incremental,
1558 // so we build a saved state file to pass.
1559 savedState = ParcelFileDescriptor.open(savedStateName,
1560 ParcelFileDescriptor.MODE_READ_ONLY |
1561 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001562
Dan Egnorbb9001c2009-07-27 12:20:13 -07001563 backupData = ParcelFileDescriptor.open(backupDataName,
1564 ParcelFileDescriptor.MODE_READ_WRITE |
1565 ParcelFileDescriptor.MODE_CREATE |
1566 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001567
Dan Egnorbb9001c2009-07-27 12:20:13 -07001568 newState = ParcelFileDescriptor.open(newStateName,
1569 ParcelFileDescriptor.MODE_READ_WRITE |
1570 ParcelFileDescriptor.MODE_CREATE |
1571 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001572
Christopher Tate44a27902010-01-27 17:15:49 -08001573 // Initiate the target's backup pass
1574 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate4a627c72011-04-01 14:43:32 -07001575 agent.doBackup(savedState, backupData, newState, false,
1576 token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001577 boolean success = waitUntilOperationComplete(token);
1578
1579 if (!success) {
1580 // timeout -- bail out into the failed-transaction logic
1581 throw new RuntimeException("Backup timeout");
1582 }
1583
Dan Egnorbb9001c2009-07-27 12:20:13 -07001584 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001586 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001588 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001589 backupDataName.delete();
1590 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001591 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001592 } finally {
1593 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1594 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1595 try { if (newState != null) newState.close(); } catch (IOException e) {}
1596 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001597 synchronized (mCurrentOpLock) {
1598 mCurrentOperations.clear();
1599 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001600 }
1601
1602 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001603 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001604 try {
1605 int size = (int) backupDataName.length();
1606 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001607 if (result == BackupConstants.TRANSPORT_OK) {
1608 backupData = ParcelFileDescriptor.open(backupDataName,
1609 ParcelFileDescriptor.MODE_READ_ONLY);
1610 result = transport.performBackup(packInfo, backupData);
1611 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001612
Dan Egnor83861e72009-09-17 16:17:55 -07001613 // TODO - We call finishBackup() for each application backed up, because
1614 // we need to know now whether it succeeded or failed. Instead, we should
1615 // hold off on finishBackup() until the end, which implies holding off on
1616 // renaming *all* the output state files (see below) until that happens.
1617
Dan Egnor01445162009-09-21 17:04:05 -07001618 if (result == BackupConstants.TRANSPORT_OK) {
1619 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001620 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001621 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001622 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 }
1624
1625 // After successful transport, delete the now-stale data
1626 // and juggle the files so that next time we supply the agent
1627 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001628 if (result == BackupConstants.TRANSPORT_OK) {
1629 backupDataName.delete();
1630 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001631 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001632 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001634 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001637 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001638 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 } finally {
1640 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001641 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001642
Dan Egnor01445162009-09-21 17:04:05 -07001643 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001644 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001645 }
1646
Christopher Tatedf01dea2009-06-09 20:45:02 -07001647
Christopher Tate4a627c72011-04-01 14:43:32 -07001648 // ----- Full backup to a file/socket -----
1649
1650 class PerformFullBackupTask implements Runnable {
1651 ParcelFileDescriptor mOutputFile;
1652 IFullBackupRestoreObserver mObserver;
1653 boolean mIncludeApks;
1654 boolean mIncludeShared;
1655 boolean mAllApps;
1656 String[] mPackages;
1657 AtomicBoolean mLatchObject;
1658 File mFilesDir;
1659 File mManifestFile;
1660
1661 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1662 boolean includeApks, boolean includeShared,
1663 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1664 mOutputFile = fd;
1665 mObserver = observer;
1666 mIncludeApks = includeApks;
1667 mIncludeShared = includeShared;
1668 mAllApps = doAllApps;
1669 mPackages = packages;
1670 mLatchObject = latch;
1671
1672 mFilesDir = new File("/data/system");
1673 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1674 }
1675
1676 @Override
1677 public void run() {
1678 final List<PackageInfo> packagesToBackup;
1679
1680 sendStartBackup();
1681
1682 // doAllApps supersedes the package set if any
1683 if (mAllApps) {
1684 packagesToBackup = mPackageManager.getInstalledPackages(
1685 PackageManager.GET_SIGNATURES);
1686 } else {
1687 packagesToBackup = new ArrayList<PackageInfo>();
1688 for (String pkgName : mPackages) {
1689 try {
1690 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1691 PackageManager.GET_SIGNATURES));
1692 } catch (NameNotFoundException e) {
1693 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1694 }
1695 }
1696 }
1697
1698 // Now back up the app data via the agent mechanism
1699 PackageInfo pkg = null;
1700 try {
1701 int N = packagesToBackup.size();
1702 for (int i = 0; i < N; i++) {
1703 pkg = packagesToBackup.get(i);
1704
1705 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1706
1707 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1708 IApplicationThread.BACKUP_MODE_FULL);
1709 if (agent != null) {
1710 try {
Christopher Tatedc92c822011-05-13 15:38:02 -07001711 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001712 boolean sendApk = mIncludeApks
1713 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1714 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1715 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1716
1717 sendOnBackupPackage(pkg.packageName);
1718
1719 {
1720 BackupDataOutput output = new BackupDataOutput(
1721 mOutputFile.getFileDescriptor());
1722
1723 if (DEBUG) Slog.d(TAG, "Writing manifest for " + pkg.packageName);
1724 writeAppManifest(pkg, mManifestFile, sendApk);
1725 FullBackup.backupToTar(pkg.packageName, null, null,
1726 mFilesDir.getAbsolutePath(),
1727 mManifestFile.getAbsolutePath(),
1728 output);
1729 }
1730
1731 if (DEBUG) Slog.d(TAG, "Calling doBackup()");
1732 final int token = generateToken();
1733 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL);
1734 agent.doBackup(null, mOutputFile, null, sendApk,
1735 token, mBackupManagerBinder);
1736 boolean success = waitUntilOperationComplete(token);
1737 if (!success) {
1738 Slog.d(TAG, "Full backup failed on package " + pkg.packageName);
1739 } else {
1740 if (DEBUG) Slog.d(TAG, "Full backup success: " + pkg.packageName);
1741 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001742 } catch (IOException e) {
1743 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
1744 }
1745 } else {
1746 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1747 }
1748 tearDown(pkg);
1749 }
1750 } catch (RemoteException e) {
1751 Slog.e(TAG, "App died during full backup");
1752 } finally {
1753 if (pkg != null) {
1754 tearDown(pkg);
1755 }
1756 try {
1757 mOutputFile.close();
1758 } catch (IOException e) {
1759 /* nothing we can do about this */
1760 }
1761 synchronized (mCurrentOpLock) {
1762 mCurrentOperations.clear();
1763 }
1764 synchronized (mLatchObject) {
1765 mLatchObject.set(true);
1766 mLatchObject.notifyAll();
1767 }
1768 sendEndBackup();
1769 mWakelock.release();
1770 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1771 }
1772 }
1773
1774 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1775 throws IOException {
1776 // Manifest format. All data are strings ending in LF:
1777 // BACKUP_MANIFEST_VERSION, currently 1
1778 //
1779 // Version 1:
1780 // package name
1781 // package's versionCode
1782 // boolean: "1" if archive includes .apk, "0" otherwise
1783 // number of signatures == N
1784 // N*: signature byte array in ascii format per Signature.toCharsString()
1785 StringBuilder builder = new StringBuilder(4096);
1786 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
1787
1788 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
1789 printer.println(pkg.packageName);
1790 printer.println(Integer.toString(pkg.versionCode));
1791 printer.println(withApk ? "1" : "0");
1792 if (pkg.signatures == null) {
1793 printer.println("0");
1794 } else {
1795 printer.println(Integer.toString(pkg.signatures.length));
1796 for (Signature sig : pkg.signatures) {
1797 printer.println(sig.toCharsString());
1798 }
1799 }
1800
1801 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07001802 outstream.write(builder.toString().getBytes());
1803 outstream.close();
1804 }
1805
1806 private void tearDown(PackageInfo pkg) {
1807 final ApplicationInfo app = pkg.applicationInfo;
1808 try {
1809 // unbind and tidy up even on timeout or failure, just in case
1810 mActivityManager.unbindBackupAgent(app);
1811
Christopher Tatedc92c822011-05-13 15:38:02 -07001812 // The agent was running with a stub Application object, so shut it down.
1813 // !!! We hardcode the confirmation UI's package name here rather than use a
1814 // manifest flag! TODO something less direct.
1815 if (app.uid != Process.SYSTEM_UID
1816 && !pkg.packageName.equals("com.android.backupconfirm")) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001817 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
1818 mActivityManager.killApplicationProcess(app.processName, app.uid);
1819 } else {
1820 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
1821 }
1822 } catch (RemoteException e) {
1823 Slog.d(TAG, "Lost app trying to shut down");
1824 }
1825 }
1826
1827 // wrappers for observer use
1828 void sendStartBackup() {
1829 if (mObserver != null) {
1830 try {
1831 mObserver.onStartBackup();
1832 } catch (RemoteException e) {
1833 Slog.w(TAG, "full backup observer went away: startBackup");
1834 mObserver = null;
1835 }
1836 }
1837 }
1838
1839 void sendOnBackupPackage(String name) {
1840 if (mObserver != null) {
1841 try {
1842 // TODO: use a more user-friendly name string
1843 mObserver.onBackupPackage(name);
1844 } catch (RemoteException e) {
1845 Slog.w(TAG, "full backup observer went away: backupPackage");
1846 mObserver = null;
1847 }
1848 }
1849 }
1850
1851 void sendEndBackup() {
1852 if (mObserver != null) {
1853 try {
1854 mObserver.onEndBackup();
1855 } catch (RemoteException e) {
1856 Slog.w(TAG, "full backup observer went away: endBackup");
1857 mObserver = null;
1858 }
1859 }
1860 }
1861 }
1862
1863
Christopher Tatedf01dea2009-06-09 20:45:02 -07001864 // ----- Restore handling -----
1865
Christopher Tate78dd4a72009-11-04 11:49:08 -08001866 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1867 // If the target resides on the system partition, we allow it to restore
1868 // data from the like-named package in a restore set even if the signatures
1869 // do not match. (Unlike general applications, those flashed to the system
1870 // partition will be signed with the device's platform certificate, so on
1871 // different phones the same system app will have different signatures.)
1872 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001873 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001874 return true;
1875 }
1876
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001877 // Allow unsigned apps, but not signed on one device and unsigned on the other
1878 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001879 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001880 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001881 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001882 if ((storedSigs == null || storedSigs.length == 0)
1883 && (deviceSigs == null || deviceSigs.length == 0)) {
1884 return true;
1885 }
1886 if (storedSigs == null || deviceSigs == null) {
1887 return false;
1888 }
1889
Christopher Tateabce4e82009-06-18 18:35:32 -07001890 // !!! TODO: this demands that every stored signature match one
1891 // that is present on device, and does not demand the converse.
1892 // Is this this right policy?
1893 int nStored = storedSigs.length;
1894 int nDevice = deviceSigs.length;
1895
1896 for (int i=0; i < nStored; i++) {
1897 boolean match = false;
1898 for (int j=0; j < nDevice; j++) {
1899 if (storedSigs[i].equals(deviceSigs[j])) {
1900 match = true;
1901 break;
1902 }
1903 }
1904 if (!match) {
1905 return false;
1906 }
1907 }
1908 return true;
1909 }
1910
Christopher Tate44a27902010-01-27 17:15:49 -08001911 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001912 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001913 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001914 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001915 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001916 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001917 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001918 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001919
Christopher Tate5cbbf562009-06-22 16:44:51 -07001920 class RestoreRequest {
1921 public PackageInfo app;
1922 public int storedAppVersion;
1923
1924 RestoreRequest(PackageInfo _app, int _version) {
1925 app = _app;
1926 storedAppVersion = _version;
1927 }
1928 }
1929
Christopher Tate44a27902010-01-27 17:15:49 -08001930 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001931 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1932 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001933 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001934 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001935 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001936 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001937 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001938 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001939
1940 try {
1941 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1942 } catch (RemoteException e) {
1943 // can't happen; the transport is local
1944 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001945 }
1946
Christopher Tatedf01dea2009-06-09 20:45:02 -07001947 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001948 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001949 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001950 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001951 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001952
Christopher Tateb49ceb32010-02-08 16:22:24 -08001953 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001954 int error = -1; // assume error
1955
Dan Egnorefe52642009-06-24 00:16:33 -07001956 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001957 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001958 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001959 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001960
Dan Egnorefe52642009-06-24 00:16:33 -07001961 // Get the list of all packages which have backup enabled.
1962 // (Include the Package Manager metadata pseudo-package first.)
1963 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1964 PackageInfo omPackage = new PackageInfo();
1965 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1966 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001967
Dan Egnorefe52642009-06-24 00:16:33 -07001968 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001969 if (mTargetPackage == null) {
1970 restorePackages.addAll(agentPackages);
1971 } else {
1972 // Just one package to attempt restore of
1973 restorePackages.add(mTargetPackage);
1974 }
Dan Egnorefe52642009-06-24 00:16:33 -07001975
Christopher Tate7d562ec2009-06-25 18:03:43 -07001976 // let the observer know that we're running
1977 if (mObserver != null) {
1978 try {
1979 // !!! TODO: get an actual count from the transport after
1980 // its startRestore() runs?
1981 mObserver.restoreStarting(restorePackages.size());
1982 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001984 mObserver = null;
1985 }
1986 }
1987
Dan Egnor01445162009-09-21 17:04:05 -07001988 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1989 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001990 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001991 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001992 return;
1993 }
1994
1995 String packageName = mTransport.nextRestorePackage();
1996 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001997 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001998 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001999 return;
2000 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002001 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002002 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002003 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07002004 return;
2005 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002006 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07002007 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002008 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002009 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002010 return;
2011 }
2012
2013 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08002014 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07002015 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07002016 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
2017 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07002018
Christopher Tate8c032472009-07-02 14:28:47 -07002019 // Verify that the backup set includes metadata. If not, we can't do
2020 // signature/version verification etc, so we simply do not proceed with
2021 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07002022 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002023 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002024 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002025 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07002026 return;
2027 }
2028
Christopher Tate7d562ec2009-06-25 18:03:43 -07002029 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07002030 for (;;) {
2031 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002032
Dan Egnorefe52642009-06-24 00:16:33 -07002033 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002034 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002035 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07002036 return;
2037 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002038 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07002039 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002040 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002041
Christopher Tate7d562ec2009-06-25 18:03:43 -07002042 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07002043 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07002044 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07002045 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002047 mObserver = null;
2048 }
2049 }
2050
Dan Egnorefe52642009-06-24 00:16:33 -07002051 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
2052 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002053 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002054 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002055 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002056 continue;
2057 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002058
Dan Egnorbb9001c2009-07-27 12:20:13 -07002059 PackageInfo packageInfo;
2060 try {
2061 int flags = PackageManager.GET_SIGNATURES;
2062 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
2063 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002064 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002065 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002066 "Package missing on device");
2067 continue;
2068 }
2069
Dan Egnorefe52642009-06-24 00:16:33 -07002070 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08002071 // Data is from a "newer" version of the app than we have currently
2072 // installed. If the app has not declared that it is prepared to
2073 // handle this case, we do not attempt the restore.
2074 if ((packageInfo.applicationInfo.flags
2075 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
2076 String message = "Version " + metaInfo.versionCode
2077 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002078 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08002079 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
2080 packageName, message);
2081 continue;
2082 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002083 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08002084 + " > installed " + packageInfo.versionCode
2085 + " but restoreAnyVersion");
2086 }
Dan Egnorefe52642009-06-24 00:16:33 -07002087 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002088
Christopher Tate78dd4a72009-11-04 11:49:08 -08002089 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002090 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002091 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002092 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07002093 continue;
2094 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002095
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07002097 + " restore version [" + metaInfo.versionCode
2098 + "] is compatible with installed version ["
2099 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07002100
Christopher Tate3de55bc2010-03-12 17:28:08 -08002101 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07002102 IBackupAgent agent = bindToAgentSynchronous(
2103 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08002104 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07002105 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002106 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002107 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002108 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002109 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002110 }
2111
Christopher Tate5e1ab332009-09-01 20:32:49 -07002112 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07002113 try {
Chris Tate249345b2010-10-29 12:57:04 -07002114 processOneRestore(packageInfo, metaInfo.versionCode, agent,
2115 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002116 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07002117 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07002118 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07002119 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07002120
2121 // The agent was probably running with a stub Application object,
2122 // which isn't a valid run mode for the main app logic. Shut
2123 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08002124 // usual full initialization. Note that this is only done for
2125 // full-system restores: when a single app has requested a restore,
2126 // it is explicitly not killed following that operation.
2127 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07002128 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002129 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07002130 + packageInfo.applicationInfo.processName);
2131 mActivityManager.killApplicationProcess(
2132 packageInfo.applicationInfo.processName,
2133 packageInfo.applicationInfo.uid);
2134 }
Dan Egnorefe52642009-06-24 00:16:33 -07002135 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002136 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002137
2138 // if we get this far, report success to the observer
2139 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002140 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002141 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002142 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002143 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002144 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002145 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002146
Dan Egnorefe52642009-06-24 00:16:33 -07002147 try {
2148 mTransport.finishRestore();
2149 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002150 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002151 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002152
2153 if (mObserver != null) {
2154 try {
2155 mObserver.restoreFinished(error);
2156 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002157 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002158 }
2159 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002160
Christopher Tate84725812010-02-04 15:52:40 -08002161 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08002162 // ancestral dataset, as well as the set of apps that are possibly
2163 // restoreable from the dataset
2164 if (mTargetPackage == null && pmAgent != null) {
2165 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08002166 mAncestralToken = mToken;
2167 writeRestoreTokens();
2168 }
2169
Christopher Tate1bb69062010-02-19 17:02:12 -08002170 // We must under all circumstances tell the Package Manager to
2171 // proceed with install notifications if it's waiting for us.
2172 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002173 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08002174 try {
2175 mPackageManagerBinder.finishPackageInstall(mPmToken);
2176 } catch (RemoteException e) { /* can't happen */ }
2177 }
2178
Christopher Tate73a3cb32010-12-13 18:27:26 -08002179 // Furthermore we need to reset the session timeout clock
2180 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2181 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
2182 TIMEOUT_RESTORE_INTERVAL);
2183
Christopher Tateb6787f22009-07-02 17:40:45 -07002184 // done; we can finally release the wakelock
2185 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07002186 }
2187 }
2188
Dan Egnorefe52642009-06-24 00:16:33 -07002189 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07002190 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
2191 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07002192 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07002193 final String packageName = app.packageName;
2194
Joe Onorato8a9b2202010-02-26 18:56:32 -08002195 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002196
Christopher Tatec7b31e32009-06-10 15:49:30 -07002197 // !!! TODO: get the dirs from the transport
2198 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002199 File newStateName = new File(mStateDir, packageName + ".new");
2200 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002201
Dan Egnorbb9001c2009-07-27 12:20:13 -07002202 ParcelFileDescriptor backupData = null;
2203 ParcelFileDescriptor newState = null;
2204
Christopher Tate4a627c72011-04-01 14:43:32 -07002205 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002206 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07002207 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07002208 backupData = ParcelFileDescriptor.open(backupDataName,
2209 ParcelFileDescriptor.MODE_READ_WRITE |
2210 ParcelFileDescriptor.MODE_CREATE |
2211 ParcelFileDescriptor.MODE_TRUNCATE);
2212
Dan Egnor01445162009-09-21 17:04:05 -07002213 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002214 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002215 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002216 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07002217 }
2218
2219 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07002220 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002221 backupData = ParcelFileDescriptor.open(backupDataName,
2222 ParcelFileDescriptor.MODE_READ_ONLY);
2223
Dan Egnorbb9001c2009-07-27 12:20:13 -07002224 newState = ParcelFileDescriptor.open(newStateName,
2225 ParcelFileDescriptor.MODE_READ_WRITE |
2226 ParcelFileDescriptor.MODE_CREATE |
2227 ParcelFileDescriptor.MODE_TRUNCATE);
2228
Christopher Tate44a27902010-01-27 17:15:49 -08002229 // Kick off the restore, checking for hung agents
2230 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
2231 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
2232 boolean success = waitUntilOperationComplete(token);
2233
2234 if (!success) {
2235 throw new RuntimeException("restore timeout");
2236 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002237
2238 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07002239 //
2240 // !!! TODO: the restored data should be migrated on the server
2241 // side into the current dataset. In that case the new state file
2242 // we just created would reflect the data already extant in the
2243 // backend, so there'd be nothing more to do. Until that happens,
2244 // however, we need to make sure that we record the data to the
2245 // current backend dataset. (Yes, this means shipping the data over
2246 // the wire in both directions. That's bad, but consistency comes
2247 // first, then efficiency.) Once we introduce server-side data
2248 // migration to the newly-restored device's dataset, we will change
2249 // the following from a discard of the newly-written state to the
2250 // "correct" operation of renaming into the canonical state blob.
2251 newStateName.delete(); // TODO: remove; see above comment
2252 //newStateName.renameTo(savedStateName); // TODO: replace with this
2253
Dan Egnorbb9001c2009-07-27 12:20:13 -07002254 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002255 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002256 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002257 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002258 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07002259
Christopher Tate96733042009-07-20 14:49:13 -07002260 // If the agent fails restore, it might have put the app's data
2261 // into an incoherent state. For consistency we wipe its data
2262 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07002263 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07002264 } finally {
2265 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002266 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2267 try { if (newState != null) newState.close(); } catch (IOException e) {}
2268 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07002269 synchronized (mCurrentOperations) {
2270 mCurrentOperations.delete(token);
2271 }
Chris Tate249345b2010-10-29 12:57:04 -07002272
2273 // If we know a priori that we'll need to perform a full post-restore backup
2274 // pass, clear the new state file data. This means we're discarding work that
2275 // was just done by the app's agent, but this way the agent doesn't need to
2276 // take any special action based on global device state.
2277 if (needFullBackup) {
2278 newStateName.delete();
2279 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002280 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002281 }
2282 }
2283
Christopher Tate44a27902010-01-27 17:15:49 -08002284 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002285 IBackupTransport mTransport;
2286 PackageInfo mPackage;
2287
Christopher Tate44a27902010-01-27 17:15:49 -08002288 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002289 mTransport = transport;
2290 mPackage = packageInfo;
2291 }
2292
Christopher Tateee0e78a2009-07-02 11:17:03 -07002293 public void run() {
2294 try {
2295 // Clear the on-device backup state to ensure a full backup next time
2296 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
2297 File stateFile = new File(stateDir, mPackage.packageName);
2298 stateFile.delete();
2299
2300 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07002301 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002302 mTransport.clearBackupData(mPackage);
2303 } catch (RemoteException e) {
2304 // can't happen; the transport is local
2305 } finally {
2306 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07002307 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002308 mTransport.finishBackup();
2309 } catch (RemoteException e) {
2310 // can't happen; the transport is local
2311 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002312
2313 // Last but not least, release the cpu
2314 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002315 }
2316 }
2317 }
2318
Christopher Tate44a27902010-01-27 17:15:49 -08002319 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002320 HashSet<String> mQueue;
2321
Christopher Tate44a27902010-01-27 17:15:49 -08002322 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002323 mQueue = transportNames;
2324 }
2325
Christopher Tate4cc86e12009-09-21 19:36:51 -07002326 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002327 try {
2328 for (String transportName : mQueue) {
2329 IBackupTransport transport = getTransport(transportName);
2330 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002331 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002332 continue;
2333 }
2334
Joe Onorato8a9b2202010-02-26 18:56:32 -08002335 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002336 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002337 long startRealtime = SystemClock.elapsedRealtime();
2338 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002339
Christopher Tate4cc86e12009-09-21 19:36:51 -07002340 if (status == BackupConstants.TRANSPORT_OK) {
2341 status = transport.finishBackup();
2342 }
2343
2344 // Okay, the wipe really happened. Clean up our local bookkeeping.
2345 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002346 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002347 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002348 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002349 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002351 synchronized (mQueueLock) {
2352 recordInitPendingLocked(false, transportName);
2353 }
Dan Egnor726247c2009-09-29 19:12:31 -07002354 } else {
2355 // If this didn't work, requeue this one and try again
2356 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002357 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002358 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002359 synchronized (mQueueLock) {
2360 recordInitPendingLocked(true, transportName);
2361 }
2362 // do this via another alarm to make sure of the wakelock states
2363 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002364 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002365 + transportName + " resched in " + delay);
2366 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2367 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002368 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002369 }
2370 } catch (RemoteException e) {
2371 // can't happen; the transports are local
2372 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002373 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002374 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002375 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002376 mWakelock.release();
2377 }
2378 }
2379 }
2380
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002381 private void dataChangedImpl(String packageName) {
2382 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2383 dataChangedImpl(packageName, targets);
2384 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002385
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002386 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002387 // Record that we need a backup pass for the caller. Since multiple callers
2388 // may share a uid, we need to note all candidates within that uid and schedule
2389 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002390 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002391
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002392 if (targets == null) {
2393 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2394 + " uid=" + Binder.getCallingUid());
2395 return;
2396 }
2397
2398 synchronized (mQueueLock) {
2399 // Note that this client has made data changes that need to be backed up
2400 for (ApplicationInfo app : targets) {
2401 // validate the caller-supplied package name against the known set of
2402 // packages associated with this uid
2403 if (app.packageName.equals(packageName)) {
2404 // Add the caller to the set of pending backups. If there is
2405 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07002406 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08002407 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002408 // Journal this request in case of crash. The put()
2409 // operation returned null when this package was not already
2410 // in the set; we want to avoid touching the disk redundantly.
2411 writeToJournalLocked(packageName);
2412
2413 if (DEBUG) {
2414 int numKeys = mPendingBackups.size();
2415 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2416 for (BackupRequest b : mPendingBackups.values()) {
2417 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2418 }
2419 }
2420 }
2421 }
2422 }
2423 }
2424 }
2425
2426 // Note: packageName is currently unused, but may be in the future
2427 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002428 // If the caller does not hold the BACKUP permission, it can only request a
2429 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002430 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002431 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002432 synchronized (mBackupParticipants) {
2433 return mBackupParticipants.get(Binder.getCallingUid());
2434 }
2435 }
2436
2437 // a caller with full permission can ask to back up any participating app
2438 // !!! TODO: allow backup of ANY app?
2439 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2440 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002441 int N = mBackupParticipants.size();
2442 for (int i = 0; i < N; i++) {
2443 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2444 if (s != null) {
2445 targets.addAll(s);
2446 }
2447 }
2448 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002449 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002450 }
Christopher Tate46758122009-05-06 11:22:00 -07002451
Christopher Tatecde87f42009-06-12 12:55:53 -07002452 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002453 RandomAccessFile out = null;
2454 try {
2455 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2456 out = new RandomAccessFile(mJournal, "rws");
2457 out.seek(out.length());
2458 out.writeUTF(str);
2459 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002460 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002461 mJournal = null;
2462 } finally {
2463 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002464 }
2465 }
2466
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002467 // ----- IBackupManager binder interface -----
2468
2469 public void dataChanged(final String packageName) {
2470 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2471 if (targets == null) {
2472 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2473 + " uid=" + Binder.getCallingUid());
2474 return;
2475 }
2476
2477 mBackupHandler.post(new Runnable() {
2478 public void run() {
2479 dataChangedImpl(packageName, targets);
2480 }
2481 });
2482 }
2483
Christopher Tateee0e78a2009-07-02 11:17:03 -07002484 // Clear the given package's backup data from the current transport
2485 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002486 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002487 PackageInfo info;
2488 try {
2489 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2490 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002491 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002492 return;
2493 }
2494
2495 // If the caller does not hold the BACKUP permission, it can only request a
2496 // wipe of its own backed-up data.
2497 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002498 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002499 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2500 apps = mBackupParticipants.get(Binder.getCallingUid());
2501 } else {
2502 // a caller with full permission can ask to back up any participating app
2503 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002504 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002505 apps = new HashSet<ApplicationInfo>();
2506 int N = mBackupParticipants.size();
2507 for (int i = 0; i < N; i++) {
2508 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2509 if (s != null) {
2510 apps.addAll(s);
2511 }
2512 }
2513 }
2514
2515 // now find the given package in the set of candidate apps
2516 for (ApplicationInfo app : apps) {
2517 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002518 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002519 // found it; fire off the clear request
2520 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002521 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002522 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002523 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2524 new ClearParams(getTransport(mCurrentTransport), info));
2525 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002526 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002527 }
2528 break;
2529 }
2530 }
2531 }
2532
Christopher Tateace7f092009-06-15 18:07:25 -07002533 // Run a backup pass immediately for any applications that have declared
2534 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002535 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002536 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002537
Joe Onorato8a9b2202010-02-26 18:56:32 -08002538 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002539 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002540 // Because the alarms we are using can jitter, and we want an *immediate*
2541 // backup pass to happen, we restart the timer beginning with "next time,"
2542 // then manually fire the backup trigger intent ourselves.
2543 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002544 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002545 mRunBackupIntent.send();
2546 } catch (PendingIntent.CanceledException e) {
2547 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002548 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002549 }
Christopher Tate46758122009-05-06 11:22:00 -07002550 }
2551 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002552
Christopher Tate4a627c72011-04-01 14:43:32 -07002553 // Run a *full* backup pass for the given package, writing the resulting data stream
2554 // to the supplied file descriptor. This method is synchronous and does not return
2555 // to the caller until the backup has been completed.
2556 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
2557 boolean doAllApps, String[] pkgList) {
2558 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2559
2560 // Validate
2561 if (!doAllApps) {
2562 if (!includeShared) {
2563 // If we're backing up shared data (sdcard or equivalent), then we can run
2564 // without any supplied app names. Otherwise, we'd be doing no work, so
2565 // report the error.
2566 if (pkgList == null || pkgList.length == 0) {
2567 throw new IllegalArgumentException(
2568 "Backup requested but neither shared nor any apps named");
2569 }
2570 }
2571 }
2572
2573 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
2574 + " shared=" + includeShared + " all=" + doAllApps
2575 + " pkgs=" + pkgList);
2576
2577 long oldId = Binder.clearCallingIdentity();
2578 try {
2579 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
2580 doAllApps, pkgList);
2581 final int token = generateToken();
2582 synchronized (mFullConfirmations) {
2583 mFullConfirmations.put(token, params);
2584 }
2585
2586 // start up the confirmation UI, making sure the screen lights up
2587 if (DEBUG) Slog.d(TAG, "Starting confirmation UI, token=" + token);
2588 try {
2589 Intent confIntent = new Intent(FullBackup.FULL_BACKUP_INTENT_ACTION);
2590 confIntent.setClassName("com.android.backupconfirm",
2591 "com.android.backupconfirm.BackupRestoreConfirmation");
2592 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
2593 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2594 mContext.startActivity(confIntent);
2595 } catch (ActivityNotFoundException e) {
2596 Slog.e(TAG, "Unable to launch full backup confirmation", e);
2597 mFullConfirmations.delete(token);
2598 return;
2599 }
2600 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
2601
2602 // start the confirmation countdown
2603 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
2604 + TIMEOUT_FULL_CONFIRMATION + " millis");
2605 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
2606 token, 0, params);
2607 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
2608
2609 // wait for the backup to be performed
2610 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
2611 waitForCompletion(params);
2612 if (DEBUG) Slog.d(TAG, "...Full backup operation complete!");
2613 } finally {
2614 Binder.restoreCallingIdentity(oldId);
2615 try {
2616 fd.close();
2617 } catch (IOException e) {
2618 // just eat it
2619 }
2620 }
2621 }
2622
2623 void waitForCompletion(FullParams params) {
2624 synchronized (params.latch) {
2625 while (params.latch.get() == false) {
2626 try {
2627 params.latch.wait();
2628 } catch (InterruptedException e) { /* never interrupted */ }
2629 }
2630 }
2631 }
2632
2633 void signalFullBackupRestoreCompletion(FullParams params) {
2634 synchronized (params.latch) {
2635 params.latch.set(true);
2636 params.latch.notifyAll();
2637 }
2638 }
2639
2640 // Confirm that the previously-requested full backup/restore operation can proceed. This
2641 // is used to require a user-facing disclosure about the operation.
2642 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
2643 IFullBackupRestoreObserver observer) {
2644 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
2645 + " allow=" + allow);
2646
2647 // TODO: possibly require not just this signature-only permission, but even
2648 // require that the specific designated confirmation-UI app uid is the caller?
2649 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2650
2651 long oldId = Binder.clearCallingIdentity();
2652 try {
2653
2654 FullParams params;
2655 synchronized (mFullConfirmations) {
2656 params = mFullConfirmations.get(token);
2657 if (params != null) {
2658 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
2659 mFullConfirmations.delete(token);
2660
2661 if (allow) {
2662 params.observer = observer;
2663 final int verb = params instanceof FullBackupParams
2664 ? MSG_RUN_FULL_BACKUP
2665 : MSG_RUN_FULL_RESTORE;
2666
2667 mWakelock.acquire();
2668 Message msg = mBackupHandler.obtainMessage(verb, params);
2669 mBackupHandler.sendMessage(msg);
2670 } else {
2671 Slog.w(TAG, "User rejected full backup/restore operation");
2672 // indicate completion without having actually transferred any data
2673 signalFullBackupRestoreCompletion(params);
2674 }
2675 } else {
2676 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
2677 }
2678 }
2679 } finally {
2680 Binder.restoreCallingIdentity(oldId);
2681 }
2682 }
2683
Christopher Tate8031a3d2009-07-06 16:36:05 -07002684 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002685 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002686 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07002687 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002688
Joe Onorato8a9b2202010-02-26 18:56:32 -08002689 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002690
Christopher Tate6ef58a12009-06-29 14:56:28 -07002691 boolean wasEnabled = mEnabled;
2692 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002693 Settings.Secure.putInt(mContext.getContentResolver(),
2694 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002695 mEnabled = enable;
2696 }
2697
Christopher Tate49401dd2009-07-01 12:34:29 -07002698 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002699 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002700 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002701 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002702 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002703 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002704 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002705
Christopher Tateb6787f22009-07-02 17:40:45 -07002706 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002707
2708 // This also constitutes an opt-out, so we wipe any data for
2709 // this device from the backend. We start that process with
2710 // an alarm in order to guarantee wakelock states.
2711 if (wasEnabled && mProvisioned) {
2712 // NOTE: we currently flush every registered transport, not just
2713 // the currently-active one.
2714 HashSet<String> allTransports;
2715 synchronized (mTransports) {
2716 allTransports = new HashSet<String>(mTransports.keySet());
2717 }
2718 // build the set of transports for which we are posting an init
2719 for (String transport : allTransports) {
2720 recordInitPendingLocked(true, transport);
2721 }
2722 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2723 mRunInitIntent);
2724 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002725 }
2726 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002727 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002728
Christopher Tatecce9da52010-02-03 15:11:15 -08002729 // Enable/disable automatic restore of app data at install time
2730 public void setAutoRestore(boolean doAutoRestore) {
2731 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2732 "setBackupEnabled");
2733
Joe Onorato8a9b2202010-02-26 18:56:32 -08002734 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002735
2736 synchronized (this) {
2737 Settings.Secure.putInt(mContext.getContentResolver(),
2738 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2739 mAutoRestore = doAutoRestore;
2740 }
2741 }
2742
Christopher Tate8031a3d2009-07-06 16:36:05 -07002743 // Mark the backup service as having been provisioned
2744 public void setBackupProvisioned(boolean available) {
2745 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2746 "setBackupProvisioned");
2747
2748 boolean wasProvisioned = mProvisioned;
2749 synchronized (this) {
2750 Settings.Secure.putInt(mContext.getContentResolver(),
2751 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2752 mProvisioned = available;
2753 }
2754
2755 synchronized (mQueueLock) {
2756 if (available && !wasProvisioned && mEnabled) {
2757 // we're now good to go, so start the backup alarms
2758 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2759 } else if (!available) {
2760 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002761 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002762 mAlarmManager.cancel(mRunBackupIntent);
2763 }
2764 }
2765 }
2766
2767 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002768 // We used to use setInexactRepeating(), but that may be linked to
2769 // backups running at :00 more often than not, creating load spikes.
2770 // Schedule at an exact time for now, and also add a bit of "fuzz".
2771
2772 Random random = new Random();
2773 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2774 random.nextInt(FUZZ_MILLIS);
2775 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2776 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002777 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002778 }
2779
Christopher Tate6ef58a12009-06-29 14:56:28 -07002780 // Report whether the backup mechanism is currently enabled
2781 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002783 return mEnabled; // no need to synchronize just to read it
2784 }
2785
Christopher Tate91717492009-06-26 21:07:13 -07002786 // Report the name of the currently active transport
2787 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002789 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002790 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002791 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002792 }
2793
Christopher Tate91717492009-06-26 21:07:13 -07002794 // Report all known, available backup transports
2795 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002797
Christopher Tate91717492009-06-26 21:07:13 -07002798 String[] list = null;
2799 ArrayList<String> known = new ArrayList<String>();
2800 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2801 if (entry.getValue() != null) {
2802 known.add(entry.getKey());
2803 }
2804 }
2805
2806 if (known.size() > 0) {
2807 list = new String[known.size()];
2808 known.toArray(list);
2809 }
2810 return list;
2811 }
2812
2813 // Select which transport to use for the next backup operation. If the given
2814 // name is not one of the available transports, no action is taken and the method
2815 // returns null.
2816 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002817 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002818
2819 synchronized (mTransports) {
2820 String prevTransport = null;
2821 if (mTransports.get(transport) != null) {
2822 prevTransport = mCurrentTransport;
2823 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002824 Settings.Secure.putString(mContext.getContentResolver(),
2825 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002826 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002827 + " returning " + prevTransport);
2828 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002829 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002830 }
2831 return prevTransport;
2832 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002833 }
2834
Christopher Tatef5e1c292010-12-08 18:40:26 -08002835 // Supply the configuration Intent for the given transport. If the name is not one
2836 // of the available transports, or if the transport does not supply any configuration
2837 // UI, the method returns null.
2838 public Intent getConfigurationIntent(String transportName) {
2839 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2840 "getConfigurationIntent");
2841
2842 synchronized (mTransports) {
2843 final IBackupTransport transport = mTransports.get(transportName);
2844 if (transport != null) {
2845 try {
2846 final Intent intent = transport.configurationIntent();
2847 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2848 + intent);
2849 return intent;
2850 } catch (RemoteException e) {
2851 /* fall through to return null */
2852 }
2853 }
2854 }
2855
2856 return null;
2857 }
2858
2859 // Supply the configuration summary string for the given transport. If the name is
2860 // not one of the available transports, or if the transport does not supply any
2861 // summary / destination string, the method can return null.
2862 //
2863 // This string is used VERBATIM as the summary text of the relevant Settings item!
2864 public String getDestinationString(String transportName) {
2865 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2866 "getConfigurationIntent");
2867
2868 synchronized (mTransports) {
2869 final IBackupTransport transport = mTransports.get(transportName);
2870 if (transport != null) {
2871 try {
2872 final String text = transport.currentDestinationString();
2873 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2874 return text;
2875 } catch (RemoteException e) {
2876 /* fall through to return null */
2877 }
2878 }
2879 }
2880
2881 return null;
2882 }
2883
Christopher Tate043dadc2009-06-02 16:11:00 -07002884 // Callback: a requested backup agent has been instantiated. This should only
2885 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002886 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002887 synchronized(mAgentConnectLock) {
2888 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002889 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002890 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2891 mConnectedAgent = agent;
2892 mConnecting = false;
2893 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002894 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002895 + " claiming agent connected");
2896 }
2897 mAgentConnectLock.notifyAll();
2898 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002899 }
2900
2901 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2902 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002903 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002904 public void agentDisconnected(String packageName) {
2905 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002906 synchronized(mAgentConnectLock) {
2907 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2908 mConnectedAgent = null;
2909 mConnecting = false;
2910 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002911 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002912 + " claiming agent disconnected");
2913 }
2914 mAgentConnectLock.notifyAll();
2915 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002916 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002917
Christopher Tate1bb69062010-02-19 17:02:12 -08002918 // An application being installed will need a restore pass, then the Package Manager
2919 // will need to be told when the restore is finished.
2920 public void restoreAtInstall(String packageName, int token) {
2921 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002922 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002923 + " attemping install-time restore");
2924 return;
2925 }
2926
2927 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002928 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002929 + " token=" + Integer.toHexString(token));
2930
Christopher Tatef0872722010-02-25 15:22:48 -08002931 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002932 // okay, we're going to attempt a restore of this package from this restore set.
2933 // The eventual message back into the Package Manager to run the post-install
2934 // steps for 'token' will be issued from the restore handling code.
2935
2936 // We can use a synthetic PackageInfo here because:
2937 // 1. We know it's valid, since the Package Manager supplied the name
2938 // 2. Only the packageName field will be used by the restore code
2939 PackageInfo pkg = new PackageInfo();
2940 pkg.packageName = packageName;
2941
2942 mWakelock.acquire();
2943 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2944 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002945 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002946 mBackupHandler.sendMessage(msg);
2947 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002948 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2949 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002950 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002951 try {
2952 mPackageManagerBinder.finishPackageInstall(token);
2953 } catch (RemoteException e) { /* can't happen */ }
2954 }
2955 }
2956
Christopher Tate8c850b72009-06-07 19:33:20 -07002957 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002958 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2959 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2960 + " transport=" + transport);
2961
2962 boolean needPermission = true;
2963 if (transport == null) {
2964 transport = mCurrentTransport;
2965
2966 if (packageName != null) {
2967 PackageInfo app = null;
2968 try {
2969 app = mPackageManager.getPackageInfo(packageName, 0);
2970 } catch (NameNotFoundException nnf) {
2971 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2972 throw new IllegalArgumentException("Package " + packageName + " not found");
2973 }
2974
2975 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2976 // So: using the current active transport, and the caller has asked
2977 // that its own package will be restored. In this narrow use case
2978 // we do not require the caller to hold the permission.
2979 needPermission = false;
2980 }
2981 }
2982 }
2983
2984 if (needPermission) {
2985 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2986 "beginRestoreSession");
2987 } else {
2988 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2989 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002990
2991 synchronized(this) {
2992 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002993 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002994 return null;
2995 }
Chris Tate44ab8452010-11-16 15:10:49 -08002996 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08002997 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07002998 }
2999 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07003000 }
Christopher Tate043dadc2009-06-02 16:11:00 -07003001
Christopher Tate73a3cb32010-12-13 18:27:26 -08003002 void clearRestoreSession(ActiveRestoreSession currentSession) {
3003 synchronized(this) {
3004 if (currentSession != mActiveRestoreSession) {
3005 Slog.e(TAG, "ending non-current restore session");
3006 } else {
3007 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
3008 mActiveRestoreSession = null;
3009 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3010 }
3011 }
3012 }
3013
Christopher Tate44a27902010-01-27 17:15:49 -08003014 // Note that a currently-active backup agent has notified us that it has
3015 // completed the given outstanding asynchronous backup/restore operation.
3016 public void opComplete(int token) {
3017 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003018 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08003019 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
3020 mCurrentOpLock.notifyAll();
3021 }
3022 }
3023
Christopher Tate9b3905c2009-06-08 15:24:01 -07003024 // ----- Restore session -----
3025
Christopher Tate80202c82010-01-25 19:37:47 -08003026 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07003027 private static final String TAG = "RestoreSession";
3028
Chris Tate44ab8452010-11-16 15:10:49 -08003029 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003030 private IBackupTransport mRestoreTransport = null;
3031 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08003032 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003033
Chris Tate44ab8452010-11-16 15:10:49 -08003034 ActiveRestoreSession(String packageName, String transport) {
3035 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07003036 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07003037 }
3038
3039 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07003040 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04003041 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003042 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003043 if (observer == null) {
3044 throw new IllegalArgumentException("Observer must not be null");
3045 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003046
Christopher Tate73a3cb32010-12-13 18:27:26 -08003047 if (mEnded) {
3048 throw new IllegalStateException("Restore session already ended");
3049 }
3050
Christopher Tate1bb69062010-02-19 17:02:12 -08003051 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07003052 try {
Christopher Tate43383042009-07-13 15:17:13 -07003053 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003054 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003055 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07003056 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07003057 // spin off the transport request to our service thread
3058 mWakelock.acquire();
3059 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
3060 new RestoreGetSetsParams(mRestoreTransport, this, observer));
3061 mBackupHandler.sendMessage(msg);
3062 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07003063 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003064 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07003065 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08003066 } finally {
3067 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07003068 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07003069 }
3070
Christopher Tate84725812010-02-04 15:52:40 -08003071 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07003072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3073 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003074
Chris Tate44ab8452010-11-16 15:10:49 -08003075 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07003076 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003077
Christopher Tate73a3cb32010-12-13 18:27:26 -08003078 if (mEnded) {
3079 throw new IllegalStateException("Restore session already ended");
3080 }
3081
Dan Egnor0084da52009-07-29 12:57:16 -07003082 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08003083 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
3084 return -1;
3085 }
3086
3087 if (mPackageName != null) {
3088 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07003089 return -1;
3090 }
3091
Christopher Tate21ab6a52009-09-24 18:01:46 -07003092 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003093 for (int i = 0; i < mRestoreSets.length; i++) {
3094 if (token == mRestoreSets[i].token) {
3095 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07003096 mWakelock.acquire();
3097 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003098 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07003099 mBackupHandler.sendMessage(msg);
3100 Binder.restoreCallingIdentity(oldId);
3101 return 0;
3102 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003103 }
3104 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07003105
Joe Onorato8a9b2202010-02-26 18:56:32 -08003106 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07003107 return -1;
3108 }
3109
Christopher Tate84725812010-02-04 15:52:40 -08003110 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003111 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08003112
Christopher Tate73a3cb32010-12-13 18:27:26 -08003113 if (mEnded) {
3114 throw new IllegalStateException("Restore session already ended");
3115 }
3116
Chris Tate44ab8452010-11-16 15:10:49 -08003117 if (mPackageName != null) {
3118 if (! mPackageName.equals(packageName)) {
3119 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
3120 + " on session for package " + mPackageName);
3121 return -1;
3122 }
3123 }
3124
Christopher Tate84725812010-02-04 15:52:40 -08003125 PackageInfo app = null;
3126 try {
3127 app = mPackageManager.getPackageInfo(packageName, 0);
3128 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003129 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003130 return -1;
3131 }
3132
3133 // If the caller is not privileged and is not coming from the target
3134 // app's uid, throw a permission exception back to the caller.
3135 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
3136 Binder.getCallingPid(), Binder.getCallingUid());
3137 if ((perm == PackageManager.PERMISSION_DENIED) &&
3138 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003139 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08003140 + " or calling uid=" + Binder.getCallingUid());
3141 throw new SecurityException("No permission to restore other packages");
3142 }
3143
Christopher Tate7d411a32010-02-26 11:27:08 -08003144 // If the package has no backup agent, we obviously cannot proceed
3145 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003146 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08003147 return -1;
3148 }
3149
Christopher Tate84725812010-02-04 15:52:40 -08003150 // So far so good; we're allowed to try to restore this package. Now
3151 // check whether there is data for it in the current dataset, falling back
3152 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08003153 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003154
3155 // If we didn't come up with a place to look -- no ancestral dataset and
3156 // the app has never been backed up from this device -- there's nothing
3157 // to do but return failure.
3158 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08003159 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08003160 return -1;
3161 }
3162
3163 // Ready to go: enqueue the restore request and claim success
3164 long oldId = Binder.clearCallingIdentity();
3165 mWakelock.acquire();
3166 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003167 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08003168 mBackupHandler.sendMessage(msg);
3169 Binder.restoreCallingIdentity(oldId);
3170 return 0;
3171 }
3172
Christopher Tate73a3cb32010-12-13 18:27:26 -08003173 // Posted to the handler to tear down a restore session in a cleanly synchronized way
3174 class EndRestoreRunnable implements Runnable {
3175 BackupManagerService mBackupManager;
3176 ActiveRestoreSession mSession;
3177
3178 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
3179 mBackupManager = manager;
3180 mSession = session;
3181 }
3182
3183 public void run() {
3184 // clean up the session's bookkeeping
3185 synchronized (mSession) {
3186 try {
3187 if (mSession.mRestoreTransport != null) {
3188 mSession.mRestoreTransport.finishRestore();
3189 }
3190 } catch (Exception e) {
3191 Slog.e(TAG, "Error in finishRestore", e);
3192 } finally {
3193 mSession.mRestoreTransport = null;
3194 mSession.mEnded = true;
3195 }
3196 }
3197
3198 // clean up the BackupManagerService side of the bookkeeping
3199 // and cancel any pending timeout message
3200 mBackupManager.clearRestoreSession(mSession);
3201 }
3202 }
3203
Dan Egnor0084da52009-07-29 12:57:16 -07003204 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003205 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003206
Christopher Tate73a3cb32010-12-13 18:27:26 -08003207 if (mEnded) {
3208 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07003209 }
3210
Christopher Tate73a3cb32010-12-13 18:27:26 -08003211 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07003212 }
3213 }
3214
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003215 @Override
3216 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003217 long identityToken = Binder.clearCallingIdentity();
3218 try {
3219 dumpInternal(pw);
3220 } finally {
3221 Binder.restoreCallingIdentity(identityToken);
3222 }
3223 }
3224
3225 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003226 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07003227 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07003228 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08003229 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08003230 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07003231 pw.println("Last backup pass: " + mLastBackupPass
3232 + " (now = " + System.currentTimeMillis() + ')');
3233 pw.println(" next scheduled: " + mNextBackupPass);
3234
Christopher Tate91717492009-06-26 21:07:13 -07003235 pw.println("Available transports:");
3236 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003237 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
3238 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003239 IBackupTransport transport = getTransport(t);
3240 File dir = new File(mBaseStateDir, transport.transportDirName());
3241 pw.println(" destination: " + transport.currentDestinationString());
3242 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07003243 for (File f : dir.listFiles()) {
3244 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
3245 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003246 } catch (Exception e) {
3247 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003248 pw.println(" Error: " + e);
3249 }
Christopher Tate91717492009-06-26 21:07:13 -07003250 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003251
3252 pw.println("Pending init: " + mPendingInits.size());
3253 for (String s : mPendingInits) {
3254 pw.println(" " + s);
3255 }
3256
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003257 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07003258 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003259 for (int i=0; i<N; i++) {
3260 int uid = mBackupParticipants.keyAt(i);
3261 pw.print(" uid: ");
3262 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003263 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
3264 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07003265 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003266 }
3267 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003268
Christopher Tateb49ceb32010-02-08 16:22:24 -08003269 pw.println("Ancestral packages: "
3270 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07003271 if (mAncestralPackages != null) {
3272 for (String pkg : mAncestralPackages) {
3273 pw.println(" " + pkg);
3274 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08003275 }
3276
Christopher Tate73e02522009-07-15 14:18:26 -07003277 pw.println("Ever backed up: " + mEverStoredApps.size());
3278 for (String pkg : mEverStoredApps) {
3279 pw.println(" " + pkg);
3280 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003281
3282 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07003283 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07003284 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07003285 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003286 }
3287 }
Christopher Tate487529a2009-04-29 14:03:25 -07003288}