blob: 34e9cb9a78deeed395c712b263fb86ad18646446 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tate1bb69062010-02-19 17:02:12 -080020import android.app.ActivityThread;
Christopher Tateb6787f22009-07-02 17:40:45 -070021import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Oscar Montemayora8529f62009-11-18 10:14:20 -080026import android.backup.IBackupManager;
27import android.backup.IRestoreObserver;
28import android.backup.IRestoreSession;
29import android.backup.RestoreSet;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070031import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.content.Context;
33import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070036import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070037import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080038import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070039import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070041import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080042import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070045import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080050import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070052import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070053import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.os.SystemClock;
Oscar Montemayora8529f62009-11-18 10:14:20 -080057import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070058import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.util.Log;
60import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080061import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tated55e18a2009-09-21 10:12:59 -070063import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070064import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080065import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070066import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070067
Christopher Tatecde87f42009-06-12 12:55:53 -070068import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070069import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070070import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080071import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070072import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070073import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070074import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070075import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040076import java.util.ArrayList;
77import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070078import java.util.HashSet;
79import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070080import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070081import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080082import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070083
84class BackupManagerService extends IBackupManager.Stub {
85 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070086 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070087
Christopher Tate49401dd2009-07-01 12:34:29 -070088 // How often we perform a backup pass. Privileged external callers can
89 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070090 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070091
Dan Egnorc1c49c02009-10-30 17:35:39 -070092 // Random variation in backup scheduling time to avoid server load spikes
93 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
94
Christopher Tate8031a3d2009-07-06 16:36:05 -070095 // The amount of time between the initial provisioning of the device and
96 // the first backup pass.
97 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
98
Christopher Tate4cc86e12009-09-21 19:36:51 -070099 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
100 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
101 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700102 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700103 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700104 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700105 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700106 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate44a27902010-01-27 17:15:49 -0800107 private static final int MSG_TIMEOUT = 6;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700108
109 // Timeout interval for deciding that a bind or clear-data has taken too long
110 static final long TIMEOUT_INTERVAL = 10 * 1000;
111
Christopher Tate44a27902010-01-27 17:15:49 -0800112 // Timeout intervals for agent backup & restore operations
113 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
114 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
115
Christopher Tate487529a2009-04-29 14:03:25 -0700116 private Context mContext;
117 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800118 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700119 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700120 private PowerManager mPowerManager;
121 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800122 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700123
Christopher Tate73e02522009-07-15 14:18:26 -0700124 boolean mEnabled; // access to this is synchronized on 'this'
125 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800126 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700127 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800128 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
129 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700130 PendingIntent mRunBackupIntent, mRunInitIntent;
131 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700132 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700133 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700134 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700135 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700136 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700137 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700138 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700139
Christopher Tate181fafa2009-05-14 11:12:14 -0700140 BackupRequest(ApplicationInfo app, boolean isFull) {
141 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700142 fullBackup = isFull;
143 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700144
145 public String toString() {
146 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
147 }
Christopher Tate46758122009-05-06 11:22:00 -0700148 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400149 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700150 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700151 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700152
153 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700154 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700155
156 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700157 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700158
Christopher Tate043dadc2009-06-02 16:11:00 -0700159 // The thread performing the sequence of queued backups binds to each app's agent
160 // in succession. Bind notifications are asynchronously delivered through the
161 // Activity Manager; use this lock object to signal when a requested binding has
162 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700163 final Object mAgentConnectLock = new Object();
164 IBackupAgent mConnectedAgent;
165 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700166 volatile long mLastBackupPass;
167 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700168
Christopher Tate55f931a2009-09-29 17:17:34 -0700169 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700170 final Object mClearDataLock = new Object();
171 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700172
Christopher Tate91717492009-06-26 21:07:13 -0700173 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700174 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700175 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700176 String mCurrentTransport;
177 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800178 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700179
Christopher Tate73e02522009-07-15 14:18:26 -0700180 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181 public IBackupTransport transport;
182 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700183 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800184 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800185 public int pmToken; // in post-install restore, the PM's token for this transaction
Christopher Tate84725812010-02-04 15:52:40 -0800186
187 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Christopher Tate1bb69062010-02-19 17:02:12 -0800188 long _token, PackageInfo _pkg, int _pmToken) {
Christopher Tate84725812010-02-04 15:52:40 -0800189 transport = _transport;
190 observer = _obs;
191 token = _token;
192 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800193 pmToken = _pmToken;
Christopher Tate84725812010-02-04 15:52:40 -0800194 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700195
Dan Egnor156411d2009-06-26 13:20:02 -0700196 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700197 transport = _transport;
198 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700199 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800200 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800201 pmToken = 0;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700202 }
203 }
204
Christopher Tate73e02522009-07-15 14:18:26 -0700205 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700206 public IBackupTransport transport;
207 public PackageInfo packageInfo;
208
209 ClearParams(IBackupTransport _transport, PackageInfo _info) {
210 transport = _transport;
211 packageInfo = _info;
212 }
213 }
214
Christopher Tate44a27902010-01-27 17:15:49 -0800215 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
216 // token is the index of the entry in the pending-operations list.
217 static final int OP_PENDING = 0;
218 static final int OP_ACKNOWLEDGED = 1;
219 static final int OP_TIMEOUT = -1;
220
221 final SparseIntArray mCurrentOperations = new SparseIntArray();
222 final Object mCurrentOpLock = new Object();
223 final Random mTokenGenerator = new Random();
224
Christopher Tate5cb400b2009-06-25 16:03:14 -0700225 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700226 File mBaseStateDir;
227 File mDataDir;
228 File mJournalDir;
229 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700230
Christopher Tate84725812010-02-04 15:52:40 -0800231 // Keep a log of all the apps we've ever backed up, and what the
232 // dataset tokens are for both the current backup dataset and
233 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700234 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700235 HashSet<String> mEverStoredApps = new HashSet<String>();
236
Christopher Tateb49ceb32010-02-08 16:22:24 -0800237 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800238 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800239 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800240 long mAncestralToken = 0;
241 long mCurrentToken = 0;
242
Christopher Tate4cc86e12009-09-21 19:36:51 -0700243 // Persistently track the need to do a full init
244 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
245 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700246
Christopher Tate44a27902010-01-27 17:15:49 -0800247 // ----- Asynchronous backup/restore handler thread -----
248
249 private class BackupHandler extends Handler {
250 public BackupHandler(Looper looper) {
251 super(looper);
252 }
253
254 public void handleMessage(Message msg) {
255
256 switch (msg.what) {
257 case MSG_RUN_BACKUP:
258 {
259 mLastBackupPass = System.currentTimeMillis();
260 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
261
262 IBackupTransport transport = getTransport(mCurrentTransport);
263 if (transport == null) {
264 Log.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800265 mWakelock.release();
266 break;
267 }
268
269 // snapshot the pending-backup set and work on that
270 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800271 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800272 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800273 // Do we have any work to do? Construct the work queue
274 // then release the synchronization lock to actually run
275 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800276 if (mPendingBackups.size() > 0) {
277 for (BackupRequest b: mPendingBackups.values()) {
278 queue.add(b);
279 }
280 if (DEBUG) Log.v(TAG, "clearing pending backups");
281 mPendingBackups.clear();
282
283 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800284 mJournal = null;
285
Christopher Tate44a27902010-01-27 17:15:49 -0800286 }
287 }
Christopher Tatec61da312010-02-05 10:41:27 -0800288
289 if (queue.size() > 0) {
290 // At this point, we have started a new journal file, and the old
291 // file identity is being passed to the backup processing thread.
292 // When it completes successfully, that old journal file will be
293 // deleted. If we crash prior to that, the old journal is parsed
294 // at next boot and the journaled requests fulfilled.
295 (new PerformBackupTask(transport, queue, oldJournal)).run();
296 } else {
297 Log.v(TAG, "Backup requested but nothing pending");
298 mWakelock.release();
299 }
Christopher Tate44a27902010-01-27 17:15:49 -0800300 break;
301 }
302
303 case MSG_RUN_FULL_BACKUP:
304 break;
305
306 case MSG_RUN_RESTORE:
307 {
308 RestoreParams params = (RestoreParams)msg.obj;
309 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
310 (new PerformRestoreTask(params.transport, params.observer,
Christopher Tate1bb69062010-02-19 17:02:12 -0800311 params.token, params.pkgInfo, params.pmToken)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800312 break;
313 }
314
315 case MSG_RUN_CLEAR:
316 {
317 ClearParams params = (ClearParams)msg.obj;
318 (new PerformClearTask(params.transport, params.packageInfo)).run();
319 break;
320 }
321
322 case MSG_RUN_INITIALIZE:
323 {
324 HashSet<String> queue;
325
326 // Snapshot the pending-init queue and work on that
327 synchronized (mQueueLock) {
328 queue = new HashSet<String>(mPendingInits);
329 mPendingInits.clear();
330 }
331
332 (new PerformInitializeTask(queue)).run();
333 break;
334 }
335
336 case MSG_TIMEOUT:
337 {
338 synchronized (mCurrentOpLock) {
339 final int token = msg.arg1;
340 int state = mCurrentOperations.get(token, OP_TIMEOUT);
341 if (state == OP_PENDING) {
342 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
343 mCurrentOperations.put(token, OP_TIMEOUT);
344 }
345 mCurrentOpLock.notifyAll();
346 }
347 break;
348 }
349 }
350 }
351 }
352
353 // ----- Main service implementation -----
354
Christopher Tate487529a2009-04-29 14:03:25 -0700355 public BackupManagerService(Context context) {
356 mContext = context;
357 mPackageManager = context.getPackageManager();
Christopher Tate1bb69062010-02-19 17:02:12 -0800358 mPackageManagerBinder = ActivityThread.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700359 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700360
Christopher Tateb6787f22009-07-02 17:40:45 -0700361 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
362 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
363
Christopher Tate44a27902010-01-27 17:15:49 -0800364 mBackupManagerBinder = asInterface(asBinder());
365
366 // spin up the backup/restore handler thread
367 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
368 mHandlerThread.start();
369 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
370
Christopher Tate22b87872009-05-04 16:41:53 -0700371 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700372 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700373 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700374 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700375 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800376 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800377 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800378 // If Encrypted file systems is enabled or disabled, this call will return the
379 // correct directory.
380 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
381 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700382 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700383
Christopher Tate4cc86e12009-09-21 19:36:51 -0700384 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700385 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700386 IntentFilter filter = new IntentFilter();
387 filter.addAction(RUN_BACKUP_ACTION);
388 context.registerReceiver(mRunBackupReceiver, filter,
389 android.Manifest.permission.BACKUP, null);
390
391 mRunInitReceiver = new RunInitializeReceiver();
392 filter = new IntentFilter();
393 filter.addAction(RUN_INITIALIZE_ACTION);
394 context.registerReceiver(mRunInitReceiver, filter,
395 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700396
397 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700398 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
399 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
400
Christopher Tate4cc86e12009-09-21 19:36:51 -0700401 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
402 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
403 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
404
Christopher Tatecde87f42009-06-12 12:55:53 -0700405 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700406 mJournalDir = new File(mBaseStateDir, "pending");
407 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700408 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700409
Christopher Tate73e02522009-07-15 14:18:26 -0700410 // Set up the various sorts of package tracking we do
411 initPackageTracking();
412
Christopher Tateabce4e82009-06-18 18:35:32 -0700413 // Build our mapping of uid to backup client services. This implicitly
414 // schedules a backup pass on the Package Manager metadata the first
415 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700416 synchronized (mBackupParticipants) {
417 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700418 }
419
Dan Egnor87a02bc2009-06-17 02:30:10 -0700420 // Set up our transport options and initialize the default transport
421 // TODO: Have transports register themselves somehow?
422 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700423 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700424 ComponentName localName = new ComponentName(context, LocalTransport.class);
425 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700426
Christopher Tate91717492009-06-26 21:07:13 -0700427 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700428 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
429 Settings.Secure.BACKUP_TRANSPORT);
430 if ("".equals(mCurrentTransport)) {
431 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700432 }
Christopher Tate91717492009-06-26 21:07:13 -0700433 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
434
435 // Attach to the Google backup transport. When this comes up, it will set
436 // itself as the current transport because we explicitly reset mCurrentTransport
437 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700438 Intent intent = new Intent().setComponent(new ComponentName(
439 "com.google.android.backup",
440 "com.google.android.backup.BackupTransportService"));
441 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700442
Christopher Tatecde87f42009-06-12 12:55:53 -0700443 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700444 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700445 parseLeftoverJournals();
446
Christopher Tateb6787f22009-07-02 17:40:45 -0700447 // Power management
448 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
449
450 // Start the backup passes going
451 setBackupEnabled(areEnabled);
452 }
453
454 private class RunBackupReceiver extends BroadcastReceiver {
455 public void onReceive(Context context, Intent intent) {
456 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700457 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700458 if (mPendingInits.size() > 0) {
459 // If there are pending init operations, we process those
460 // and then settle into the usual periodic backup schedule.
461 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
462 try {
463 mAlarmManager.cancel(mRunInitIntent);
464 mRunInitIntent.send();
465 } catch (PendingIntent.CanceledException ce) {
466 Log.e(TAG, "Run init intent cancelled");
467 // can't really do more than bail here
468 }
469 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800470 // Don't run backups now if we're disabled or not yet
471 // fully set up.
472 if (mEnabled && mProvisioned) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700473 if (DEBUG) Log.v(TAG, "Running a backup pass");
474
475 // Acquire the wakelock and pass it to the backup thread. it will
476 // be released once backup concludes.
477 mWakelock.acquire();
478
479 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
480 mBackupHandler.sendMessage(msg);
481 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800482 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700483 }
484 }
485 }
486 }
487 }
488 }
489
490 private class RunInitializeReceiver extends BroadcastReceiver {
491 public void onReceive(Context context, Intent intent) {
492 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
493 synchronized (mQueueLock) {
494 if (DEBUG) Log.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700495
496 // Acquire the wakelock and pass it to the init thread. it will
497 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700498 mWakelock.acquire();
499
Christopher Tate4cc86e12009-09-21 19:36:51 -0700500 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700501 mBackupHandler.sendMessage(msg);
502 }
503 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700504 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700505 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700506
Christopher Tate73e02522009-07-15 14:18:26 -0700507 private void initPackageTracking() {
508 if (DEBUG) Log.v(TAG, "Initializing package tracking");
509
Christopher Tate84725812010-02-04 15:52:40 -0800510 // Remember our ancestral dataset
511 mTokenFile = new File(mBaseStateDir, "ancestral");
512 try {
513 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800514 int version = tf.readInt();
515 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
516 mAncestralToken = tf.readLong();
517 mCurrentToken = tf.readLong();
518
519 int numPackages = tf.readInt();
520 if (numPackages >= 0) {
521 mAncestralPackages = new HashSet<String>();
522 for (int i = 0; i < numPackages; i++) {
523 String pkgName = tf.readUTF();
524 mAncestralPackages.add(pkgName);
525 }
526 }
527 }
Christopher Tate1168baa2010-02-17 13:03:40 -0800528 } catch (FileNotFoundException fnf) {
529 // Probably innocuous
530 Log.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800531 } catch (IOException e) {
532 Log.w(TAG, "Unable to read token file", e);
533 }
534
Christopher Tatee97e8072009-07-15 16:45:50 -0700535 // Keep a log of what apps we've ever backed up. Because we might have
536 // rebooted in the middle of an operation that was removing something from
537 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700538 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700539 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700540
Christopher Tatee97e8072009-07-15 16:45:50 -0700541 // If we were in the middle of removing something from the ever-backed-up
542 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700543 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700544 if (tempProcessedFile.exists()) {
545 tempProcessedFile.delete();
546 }
547
Dan Egnor852f8e42009-09-30 11:20:45 -0700548 // If there are previous contents, parse them out then start a new
549 // file to continue the recordkeeping.
550 if (mEverStored.exists()) {
551 RandomAccessFile temp = null;
552 RandomAccessFile in = null;
553
554 try {
555 temp = new RandomAccessFile(tempProcessedFile, "rws");
556 in = new RandomAccessFile(mEverStored, "r");
557
558 while (true) {
559 PackageInfo info;
560 String pkg = in.readUTF();
561 try {
562 info = mPackageManager.getPackageInfo(pkg, 0);
563 mEverStoredApps.add(pkg);
564 temp.writeUTF(pkg);
565 if (DEBUG) Log.v(TAG, " + " + pkg);
566 } catch (NameNotFoundException e) {
567 // nope, this package was uninstalled; don't include it
568 if (DEBUG) Log.v(TAG, " - " + pkg);
569 }
570 }
571 } catch (EOFException e) {
572 // Once we've rewritten the backup history log, atomically replace the
573 // old one with the new one then reopen the file for continuing use.
574 if (!tempProcessedFile.renameTo(mEverStored)) {
575 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
576 }
577 } catch (IOException e) {
578 Log.e(TAG, "Error in processed file", e);
579 } finally {
580 try { if (temp != null) temp.close(); } catch (IOException e) {}
581 try { if (in != null) in.close(); } catch (IOException e) {}
582 }
583 }
584
Christopher Tate73e02522009-07-15 14:18:26 -0700585 // Register for broadcasts about package install, etc., so we can
586 // update the provider list.
587 IntentFilter filter = new IntentFilter();
588 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
589 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
590 filter.addDataScheme("package");
591 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800592 // Register for events related to sdcard installation.
593 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800594 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
595 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800596 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700597 }
598
Christopher Tatecde87f42009-06-12 12:55:53 -0700599 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700600 for (File f : mJournalDir.listFiles()) {
601 if (mJournal == null || f.compareTo(mJournal) != 0) {
602 // This isn't the current journal, so it must be a leftover. Read
603 // out the package names mentioned there and schedule them for
604 // backup.
605 RandomAccessFile in = null;
606 try {
607 Log.i(TAG, "Found stale backup journal, scheduling:");
608 in = new RandomAccessFile(f, "r");
609 while (true) {
610 String packageName = in.readUTF();
611 Log.i(TAG, " + " + packageName);
612 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700613 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700614 } catch (EOFException e) {
615 // no more data; we're done
616 } catch (Exception e) {
617 Log.e(TAG, "Can't read " + f, e);
618 } finally {
619 // close/delete the file
620 try { if (in != null) in.close(); } catch (IOException e) {}
621 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700622 }
623 }
624 }
625 }
626
Christopher Tate4cc86e12009-09-21 19:36:51 -0700627 // Maintain persistent state around whether need to do an initialize operation.
628 // Must be called with the queue lock held.
629 void recordInitPendingLocked(boolean isPending, String transportName) {
630 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
631 + " on transport " + transportName);
632 try {
633 IBackupTransport transport = getTransport(transportName);
634 String transportDirName = transport.transportDirName();
635 File stateDir = new File(mBaseStateDir, transportDirName);
636 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
637
638 if (isPending) {
639 // We need an init before we can proceed with sending backup data.
640 // Record that with an entry in our set of pending inits, as well as
641 // journaling it via creation of a sentinel file.
642 mPendingInits.add(transportName);
643 try {
644 (new FileOutputStream(initPendingFile)).close();
645 } catch (IOException ioe) {
646 // Something is badly wrong with our permissions; just try to move on
647 }
648 } else {
649 // No more initialization needed; wipe the journal and reset our state.
650 initPendingFile.delete();
651 mPendingInits.remove(transportName);
652 }
653 } catch (RemoteException e) {
654 // can't happen; the transport is local
655 }
656 }
657
Christopher Tated55e18a2009-09-21 10:12:59 -0700658 // Reset all of our bookkeeping, in response to having been told that
659 // the backend data has been wiped [due to idle expiry, for example],
660 // so we must re-upload all saved settings.
661 void resetBackupState(File stateFileDir) {
662 synchronized (mQueueLock) {
663 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700664 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700665 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700666
Christopher Tate84725812010-02-04 15:52:40 -0800667 mCurrentToken = 0;
668 writeRestoreTokens();
669
Christopher Tated55e18a2009-09-21 10:12:59 -0700670 // Remove all the state files
671 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700672 // ... but don't touch the needs-init sentinel
673 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
674 sf.delete();
675 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700676 }
677
678 // Enqueue a new backup of every participant
679 int N = mBackupParticipants.size();
680 for (int i=0; i<N; i++) {
681 int uid = mBackupParticipants.keyAt(i);
682 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
683 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700684 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700685 }
686 }
687 }
688 }
689
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800690 // Add a transport to our set of available backends. If 'transport' is null, this
691 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700692 private void registerTransport(String name, IBackupTransport transport) {
693 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700694 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800695 if (transport != null) {
696 mTransports.put(name, transport);
697 } else {
698 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800699 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800700 mCurrentTransport = null;
701 }
702 // Nothing further to do in the unregistration case
703 return;
704 }
Christopher Tate91717492009-06-26 21:07:13 -0700705 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700706
707 // If the init sentinel file exists, we need to be sure to perform the init
708 // as soon as practical. We also create the state directory at registration
709 // time to ensure it's present from the outset.
710 try {
711 String transportName = transport.transportDirName();
712 File stateDir = new File(mBaseStateDir, transportName);
713 stateDir.mkdirs();
714
715 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
716 if (initSentinel.exists()) {
717 synchronized (mQueueLock) {
718 mPendingInits.add(transportName);
719
720 // TODO: pick a better starting time than now + 1 minute
721 long delay = 1000 * 60; // one minute, in milliseconds
722 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
723 System.currentTimeMillis() + delay, mRunInitIntent);
724 }
725 }
726 } catch (RemoteException e) {
727 // can't happen, the transport is local
728 }
Christopher Tate91717492009-06-26 21:07:13 -0700729 }
730
Christopher Tate3799bc22009-05-06 16:13:56 -0700731 // ----- Track installation/removal of packages -----
732 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
733 public void onReceive(Context context, Intent intent) {
734 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
735
Christopher Tate3799bc22009-05-06 16:13:56 -0700736 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800737 boolean replacing = false;
738 boolean added = false;
739 Bundle extras = intent.getExtras();
740 String pkgList[] = null;
741 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
742 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
743 Uri uri = intent.getData();
744 if (uri == null) {
745 return;
746 }
747 String pkgName = uri.getSchemeSpecificPart();
748 if (pkgName != null) {
749 pkgList = new String[] { pkgName };
750 }
751 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
752 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800753 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800754 added = true;
755 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800756 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800757 added = false;
758 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
759 }
760 if (pkgList == null || pkgList.length == 0) {
761 return;
762 }
763 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700764 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800765 for (String pkgName : pkgList) {
766 if (replacing) {
767 // The package was just upgraded
768 updatePackageParticipantsLocked(pkgName);
769 } else {
770 // The package was just added
771 addPackageParticipantsLocked(pkgName);
772 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700773 }
774 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800775 } else {
776 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700777 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
778 } else {
779 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800780 for (String pkgName : pkgList) {
781 removePackageParticipantsLocked(pkgName);
782 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700783 }
784 }
785 }
786 }
787 };
788
Dan Egnor87a02bc2009-06-17 02:30:10 -0700789 // ----- Track connection to GoogleBackupTransport service -----
790 ServiceConnection mGoogleConnection = new ServiceConnection() {
791 public void onServiceConnected(ComponentName name, IBinder service) {
792 if (DEBUG) Log.v(TAG, "Connected to Google transport");
793 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700794 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700795 }
796
797 public void onServiceDisconnected(ComponentName name) {
798 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
799 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700800 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700801 }
802 };
803
Christopher Tate181fafa2009-05-14 11:12:14 -0700804 // Add the backup agents in the given package to our set of known backup participants.
805 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700806 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700807 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700808 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700809 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700810 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700811 }
812
Christopher Tate181fafa2009-05-14 11:12:14 -0700813 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700814 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700815 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700816 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
817 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700818 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700819 + " uid=" + p.applicationInfo.uid
820 + " killAfterRestore="
821 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
822 + " restoreNeedsApplication="
823 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
824 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700825 }
826 }
827
Dan Egnorefe52642009-06-24 00:16:33 -0700828 for (PackageInfo pkg : targetPkgs) {
829 if (packageName == null || pkg.packageName.equals(packageName)) {
830 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700831 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700832 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700833 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700834 mBackupParticipants.put(uid, set);
835 }
Dan Egnorefe52642009-06-24 00:16:33 -0700836 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700837
838 // If we've never seen this app before, schedule a backup for it
839 if (!mEverStoredApps.contains(pkg.packageName)) {
840 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
841 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700842 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700843 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700844 }
Christopher Tate487529a2009-04-29 14:03:25 -0700845 }
846 }
847
Christopher Tate6785dd82009-06-18 15:58:25 -0700848 // Remove the given package's entry from our known active set. If
849 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700850 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700851 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700852 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700854 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700855 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700856 int flags = PackageManager.GET_SIGNATURES;
857 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700858 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700859 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700860 }
861 } else {
862 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700863 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700864 }
865 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700866 }
867
Joe Onorato8ad02812009-05-13 01:41:44 -0400868 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700869 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700870 if (DEBUG) {
871 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
872 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700873 for (PackageInfo p : agents) {
874 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700875 }
876 }
Dan Egnorefe52642009-06-24 00:16:33 -0700877 for (PackageInfo pkg : agents) {
878 if (packageName == null || pkg.packageName.equals(packageName)) {
879 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700880 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700881 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700882 // Find the existing entry with the same package name, and remove it.
883 // We can't just remove(app) because the instances are different.
884 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700885 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700886 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700887 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700888 break;
889 }
890 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700891 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700892 mBackupParticipants.delete(uid);
893 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700894 }
895 }
896 }
897 }
898
Christopher Tate181fafa2009-05-14 11:12:14 -0700899 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700900 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700901 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700902 int flags = PackageManager.GET_SIGNATURES;
903 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
904 int N = packages.size();
905 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700906 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700907 try {
908 ApplicationInfo app = pkg.applicationInfo;
909 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800910 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700911 packages.remove(a);
912 }
913 else {
914 // we will need the shared library path, so look that up and store it here
915 app = mPackageManager.getApplicationInfo(pkg.packageName,
916 PackageManager.GET_SHARED_LIBRARY_FILES);
917 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
918 }
919 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700920 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700921 }
922 }
Dan Egnorefe52642009-06-24 00:16:33 -0700923 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700924 }
Christopher Tateaa088442009-06-16 18:25:46 -0700925
Christopher Tate3799bc22009-05-06 16:13:56 -0700926 // Reset the given package's known backup participants. Unlike add/remove, the update
927 // action cannot be passed a null package name.
928 void updatePackageParticipantsLocked(String packageName) {
929 if (packageName == null) {
930 Log.e(TAG, "updatePackageParticipants called with null package name");
931 return;
932 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700933 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700934
935 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700936 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700937 removePackageParticipantsLockedInner(packageName, allApps);
938 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700939 }
940
Christopher Tate84725812010-02-04 15:52:40 -0800941 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -0700942 // backed up at least once
943 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700944 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
945
946 synchronized (mEverStoredApps) {
947 if (!mEverStoredApps.add(packageName)) return;
948
949 RandomAccessFile out = null;
950 try {
951 out = new RandomAccessFile(mEverStored, "rws");
952 out.seek(out.length());
953 out.writeUTF(packageName);
954 } catch (IOException e) {
955 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
956 } finally {
957 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700958 }
959 }
960 }
961
Christopher Tatee97e8072009-07-15 16:45:50 -0700962 // Remove our awareness of having ever backed up the given package
963 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700964 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700965
Dan Egnor852f8e42009-09-30 11:20:45 -0700966 synchronized (mEverStoredApps) {
967 // Rewrite the file and rename to overwrite. If we reboot in the middle,
968 // we'll recognize on initialization time that the package no longer
969 // exists and fix it up then.
970 File tempKnownFile = new File(mBaseStateDir, "processed.new");
971 RandomAccessFile known = null;
972 try {
973 known = new RandomAccessFile(tempKnownFile, "rws");
974 mEverStoredApps.remove(packageName);
975 for (String s : mEverStoredApps) {
976 known.writeUTF(s);
977 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700978 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700979 known.close();
980 known = null;
981 if (!tempKnownFile.renameTo(mEverStored)) {
982 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
983 }
984 } catch (IOException e) {
985 // Bad: we couldn't create the new copy. For safety's sake we
986 // abandon the whole process and remove all what's-backed-up
987 // state entirely, meaning we'll force a backup pass for every
988 // participant on the next boot or [re]install.
989 Log.w(TAG, "Error rewriting " + mEverStored, e);
990 mEverStoredApps.clear();
991 tempKnownFile.delete();
992 mEverStored.delete();
993 } finally {
994 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700995 }
996 }
997 }
998
Christopher Tateb49ceb32010-02-08 16:22:24 -0800999 // Persistently record the current and ancestral backup tokens as well
1000 // as the set of packages with data [supposedly] available in the
1001 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001002 void writeRestoreTokens() {
1003 try {
1004 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001005
1006 // First, the version number of this record, for futureproofing
1007 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1008
1009 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001010 af.writeLong(mAncestralToken);
1011 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001012
1013 // Now write the set of ancestral packages
1014 if (mAncestralPackages == null) {
1015 af.writeInt(-1);
1016 } else {
1017 af.writeInt(mAncestralPackages.size());
1018 if (DEBUG) Log.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
1019 for (String pkgName : mAncestralPackages) {
1020 af.writeUTF(pkgName);
1021 if (DEBUG) Log.v(TAG, " " + pkgName);
1022 }
1023 }
Christopher Tate84725812010-02-04 15:52:40 -08001024 af.close();
1025 } catch (IOException e) {
1026 Log.w(TAG, "Unable to write token file:", e);
1027 }
1028 }
1029
Dan Egnor87a02bc2009-06-17 02:30:10 -07001030 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001031 private IBackupTransport getTransport(String transportName) {
1032 synchronized (mTransports) {
1033 IBackupTransport transport = mTransports.get(transportName);
1034 if (transport == null) {
1035 Log.w(TAG, "Requested unavailable transport: " + transportName);
1036 }
1037 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001038 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001039 }
1040
Christopher Tatedf01dea2009-06-09 20:45:02 -07001041 // fire off a backup agent, blocking until it attaches or times out
1042 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1043 IBackupAgent agent = null;
1044 synchronized(mAgentConnectLock) {
1045 mConnecting = true;
1046 mConnectedAgent = null;
1047 try {
1048 if (mActivityManager.bindBackupAgent(app, mode)) {
1049 Log.d(TAG, "awaiting agent for " + app);
1050
1051 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001052 // only wait 10 seconds for the clear data to happen
1053 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1054 while (mConnecting && mConnectedAgent == null
1055 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001056 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001057 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001058 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001059 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001060 return null;
1061 }
1062 }
1063
1064 // if we timed out with no connect, abort and move on
1065 if (mConnecting == true) {
1066 Log.w(TAG, "Timeout waiting for agent " + app);
1067 return null;
1068 }
1069 agent = mConnectedAgent;
1070 }
1071 } catch (RemoteException e) {
1072 // can't happen
1073 }
1074 }
1075 return agent;
1076 }
1077
Christopher Tatec7b31e32009-06-10 15:49:30 -07001078 // clear an application's data, blocking until the operation completes or times out
1079 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001080 // Don't wipe packages marked allowClearUserData=false
1081 try {
1082 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1083 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1084 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
1085 + packageName);
1086 return;
1087 }
1088 } catch (NameNotFoundException e) {
1089 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
1090 return;
1091 }
1092
Christopher Tatec7b31e32009-06-10 15:49:30 -07001093 ClearDataObserver observer = new ClearDataObserver();
1094
1095 synchronized(mClearDataLock) {
1096 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001097 try {
1098 mActivityManager.clearApplicationUserData(packageName, observer);
1099 } catch (RemoteException e) {
1100 // can't happen because the activity manager is in this process
1101 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001102
1103 // only wait 10 seconds for the clear data to happen
1104 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1105 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1106 try {
1107 mClearDataLock.wait(5000);
1108 } catch (InterruptedException e) {
1109 // won't happen, but still.
1110 mClearingData = false;
1111 }
1112 }
1113 }
1114 }
1115
1116 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001117 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001118 synchronized(mClearDataLock) {
1119 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001120 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001121 }
1122 }
1123 }
1124
Christopher Tate1bb69062010-02-19 17:02:12 -08001125 // Get the restore-set token for the best-available restore set for this package:
1126 // the active set if possible, else the ancestral one. Returns zero if none available.
1127 long getAvailableRestoreToken(String packageName) {
1128 long token = mAncestralToken;
1129 synchronized (mQueueLock) {
1130 if (mEverStoredApps.contains(packageName)) {
1131 token = mCurrentToken;
1132 }
1133 }
1134 return token;
1135 }
1136
Christopher Tate44a27902010-01-27 17:15:49 -08001137 // -----
1138 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1139 boolean waitUntilOperationComplete(int token) {
1140 int finalState = OP_PENDING;
1141 synchronized (mCurrentOpLock) {
1142 try {
1143 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1144 try {
1145 mCurrentOpLock.wait();
1146 } catch (InterruptedException e) {}
1147 }
1148 } catch (IndexOutOfBoundsException e) {
1149 // the operation has been mysteriously cleared from our
1150 // bookkeeping -- consider this a success and ignore it.
1151 }
1152 }
1153 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tate1bb69062010-02-19 17:02:12 -08001154 if (DEBUG) Log.v(TAG, "operation " + Integer.toHexString(token)
1155 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001156 return finalState == OP_ACKNOWLEDGED;
1157 }
1158
1159 void prepareOperationTimeout(int token, long interval) {
Christopher Tate1bb69062010-02-19 17:02:12 -08001160 if (DEBUG) Log.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1161 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001162 mCurrentOperations.put(token, OP_PENDING);
1163 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1164 mBackupHandler.sendMessageDelayed(msg, interval);
1165 }
1166
Christopher Tate043dadc2009-06-02 16:11:00 -07001167 // ----- Back up a set of applications via a worker thread -----
1168
Christopher Tate44a27902010-01-27 17:15:49 -08001169 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001170 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001171 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001172 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001173 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001174 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001175
Christopher Tate44a27902010-01-27 17:15:49 -08001176 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001177 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001178 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001179 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001180 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001181
1182 try {
1183 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1184 } catch (RemoteException e) {
1185 // can't happen; the transport is local
1186 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001187 }
1188
Christopher Tate043dadc2009-06-02 16:11:00 -07001189 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001190 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001191 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001192 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1193
Christopher Tate79588342009-06-30 16:11:49 -07001194 // Backups run at background priority
1195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1196
Christopher Tate043dadc2009-06-02 16:11:00 -07001197 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001199
Dan Egnor852f8e42009-09-30 11:20:45 -07001200 // If we haven't stored package manager metadata yet, we must init the transport.
1201 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1202 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1203 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1204 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001205 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001206 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001208 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001209 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001210 Log.e(TAG, "Transport error in initializeDevice()");
1211 }
Dan Egnor01445162009-09-21 17:04:05 -07001212 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001213
1214 // The package manager doesn't have a proper <application> etc, but since
1215 // it's running here in the system process we can just set up its agent
1216 // directly and use a synthetic BackupRequest. We always run this pass
1217 // because it's cheap and this way we guarantee that we don't get out of
1218 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001219 if (status == BackupConstants.TRANSPORT_OK) {
1220 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1221 mPackageManager, allAgentPackages());
1222 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1223 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1224 status = processOneBackup(pmRequest,
1225 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1226 }
Christopher Tate90967f42009-09-20 15:28:33 -07001227
Dan Egnor01445162009-09-21 17:04:05 -07001228 if (status == BackupConstants.TRANSPORT_OK) {
1229 // Now run all the backups in our queue
1230 status = doQueuedBackups(mTransport);
1231 }
1232
1233 if (status == BackupConstants.TRANSPORT_OK) {
1234 // Tell the transport to finish everything it has buffered
1235 status = mTransport.finishBackup();
1236 if (status == BackupConstants.TRANSPORT_OK) {
1237 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001238 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001239 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001240 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001241 Log.e(TAG, "Transport error in finishBackup()");
1242 }
1243 }
1244
Dan Egnor01445162009-09-21 17:04:05 -07001245 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001246 // The backend reports that our dataset has been wiped. We need to
1247 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001248 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001249 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001250 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001251 }
1252 } catch (Exception e) {
1253 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001254 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001256 // If everything actually went through and this is the first time we've
1257 // done a backup, we can now record what the current backup dataset token
1258 // is.
1259 if ((mCurrentToken == 0) && (status != BackupConstants.TRANSPORT_OK)) {
1260 try {
1261 mCurrentToken = mTransport.getCurrentRestoreSet();
1262 } catch (RemoteException e) { /* cannot happen */ }
1263 writeRestoreTokens();
1264 }
1265
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001266 // If things went wrong, we need to re-stage the apps we had expected
1267 // to be backing up in this pass. This journals the package names in
1268 // the current active pending-backup file, not in the we are holding
1269 // here in mJournal.
1270 if (status != BackupConstants.TRANSPORT_OK) {
1271 Log.w(TAG, "Backup pass unsuccessful, restaging");
1272 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001273 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001274 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001275
1276 // We also want to reset the backup schedule based on whatever
1277 // the transport suggests by way of retry/backoff time.
1278 try {
1279 startBackupAlarmsLocked(mTransport.requestBackupTime());
1280 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001281 }
1282
1283 // Either backup was successful, in which case we of course do not need
1284 // this pass's journal any more; or it failed, in which case we just
1285 // re-enqueued all of these packages in the current active journal.
1286 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001287 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001288 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1289 }
1290
Christopher Tatec2af5d32010-02-02 15:18:58 -08001291 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001292 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001293 backupNow();
1294 }
1295
Dan Egnorbb9001c2009-07-27 12:20:13 -07001296 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001297 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001298 }
1299
Dan Egnor01445162009-09-21 17:04:05 -07001300 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001301 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001302 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001303
1304 IBackupAgent agent = null;
1305 int mode = (request.fullBackup)
1306 ? IApplicationThread.BACKUP_MODE_FULL
1307 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1308 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001309 agent = bindToAgentSynchronous(request.appInfo, mode);
1310 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001311 int result = processOneBackup(request, agent, transport);
1312 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001313 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001314 } catch (SecurityException ex) {
1315 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001316 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001317 } finally {
1318 try { // unbind even on timeout, just in case
1319 mActivityManager.unbindBackupAgent(request.appInfo);
1320 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001321 }
1322 }
Dan Egnor01445162009-09-21 17:04:05 -07001323
1324 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001325 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001326
Dan Egnor01445162009-09-21 17:04:05 -07001327 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1328 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001329 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001330 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001331
Dan Egnorbb9001c2009-07-27 12:20:13 -07001332 File savedStateName = new File(mStateDir, packageName);
1333 File backupDataName = new File(mDataDir, packageName + ".data");
1334 File newStateName = new File(mStateDir, packageName + ".new");
1335
1336 ParcelFileDescriptor savedState = null;
1337 ParcelFileDescriptor backupData = null;
1338 ParcelFileDescriptor newState = null;
1339
1340 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001341 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001342 try {
1343 // Look up the package info & signatures. This is first so that if it
1344 // throws an exception, there's no file setup yet that would need to
1345 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001346 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1347 // The metadata 'package' is synthetic
1348 packInfo = new PackageInfo();
1349 packInfo.packageName = packageName;
1350 } else {
1351 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001352 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001353 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001354
Christopher Tatec7b31e32009-06-10 15:49:30 -07001355 // In a full backup, we pass a null ParcelFileDescriptor as
1356 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001357 if (!request.fullBackup) {
1358 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001359 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001360 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1361 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001362
Dan Egnorbb9001c2009-07-27 12:20:13 -07001363 backupData = ParcelFileDescriptor.open(backupDataName,
1364 ParcelFileDescriptor.MODE_READ_WRITE |
1365 ParcelFileDescriptor.MODE_CREATE |
1366 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001367
Dan Egnorbb9001c2009-07-27 12:20:13 -07001368 newState = ParcelFileDescriptor.open(newStateName,
1369 ParcelFileDescriptor.MODE_READ_WRITE |
1370 ParcelFileDescriptor.MODE_CREATE |
1371 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001372
Christopher Tate44a27902010-01-27 17:15:49 -08001373 // Initiate the target's backup pass
1374 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1375 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1376 boolean success = waitUntilOperationComplete(token);
1377
1378 if (!success) {
1379 // timeout -- bail out into the failed-transaction logic
1380 throw new RuntimeException("Backup timeout");
1381 }
1382
Dan Egnorbb9001c2009-07-27 12:20:13 -07001383 logBackupComplete(packageName);
1384 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001385 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001386 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001387 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001388 backupDataName.delete();
1389 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001390 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001391 } finally {
1392 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1393 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1394 try { if (newState != null) newState.close(); } catch (IOException e) {}
1395 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001396 synchronized (mCurrentOpLock) {
1397 mCurrentOperations.clear();
1398 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 }
1400
1401 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001402 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001403 try {
1404 int size = (int) backupDataName.length();
1405 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001406 if (result == BackupConstants.TRANSPORT_OK) {
1407 backupData = ParcelFileDescriptor.open(backupDataName,
1408 ParcelFileDescriptor.MODE_READ_ONLY);
1409 result = transport.performBackup(packInfo, backupData);
1410 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001411
Dan Egnor83861e72009-09-17 16:17:55 -07001412 // TODO - We call finishBackup() for each application backed up, because
1413 // we need to know now whether it succeeded or failed. Instead, we should
1414 // hold off on finishBackup() until the end, which implies holding off on
1415 // renaming *all* the output state files (see below) until that happens.
1416
Dan Egnor01445162009-09-21 17:04:05 -07001417 if (result == BackupConstants.TRANSPORT_OK) {
1418 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001419 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001420 } else {
1421 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1422 }
1423
1424 // After successful transport, delete the now-stale data
1425 // and juggle the files so that next time we supply the agent
1426 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001427 if (result == BackupConstants.TRANSPORT_OK) {
1428 backupDataName.delete();
1429 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001430 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001431 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001432 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001433 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434 } catch (Exception e) {
1435 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001436 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001437 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001438 } finally {
1439 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001440 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001441
Dan Egnor01445162009-09-21 17:04:05 -07001442 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001443 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001444 }
1445
Christopher Tatedf01dea2009-06-09 20:45:02 -07001446
1447 // ----- Restore handling -----
1448
Christopher Tate78dd4a72009-11-04 11:49:08 -08001449 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1450 // If the target resides on the system partition, we allow it to restore
1451 // data from the like-named package in a restore set even if the signatures
1452 // do not match. (Unlike general applications, those flashed to the system
1453 // partition will be signed with the device's platform certificate, so on
1454 // different phones the same system app will have different signatures.)
1455 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1456 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1457 return true;
1458 }
1459
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001460 // Allow unsigned apps, but not signed on one device and unsigned on the other
1461 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001462 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001463 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1464 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001465 if ((storedSigs == null || storedSigs.length == 0)
1466 && (deviceSigs == null || deviceSigs.length == 0)) {
1467 return true;
1468 }
1469 if (storedSigs == null || deviceSigs == null) {
1470 return false;
1471 }
1472
Christopher Tateabce4e82009-06-18 18:35:32 -07001473 // !!! TODO: this demands that every stored signature match one
1474 // that is present on device, and does not demand the converse.
1475 // Is this this right policy?
1476 int nStored = storedSigs.length;
1477 int nDevice = deviceSigs.length;
1478
1479 for (int i=0; i < nStored; i++) {
1480 boolean match = false;
1481 for (int j=0; j < nDevice; j++) {
1482 if (storedSigs[i].equals(deviceSigs[j])) {
1483 match = true;
1484 break;
1485 }
1486 }
1487 if (!match) {
1488 return false;
1489 }
1490 }
1491 return true;
1492 }
1493
Christopher Tate44a27902010-01-27 17:15:49 -08001494 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001495 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001496 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001497 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001498 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001499 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001500 private int mPmToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001501
Christopher Tate5cbbf562009-06-22 16:44:51 -07001502 class RestoreRequest {
1503 public PackageInfo app;
1504 public int storedAppVersion;
1505
1506 RestoreRequest(PackageInfo _app, int _version) {
1507 app = _app;
1508 storedAppVersion = _version;
1509 }
1510 }
1511
Christopher Tate44a27902010-01-27 17:15:49 -08001512 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate1bb69062010-02-19 17:02:12 -08001513 long restoreSetToken, PackageInfo targetPackage, int pmToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001514 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001515 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001516 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001517 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001518 mPmToken = pmToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001519
1520 try {
1521 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1522 } catch (RemoteException e) {
1523 // can't happen; the transport is local
1524 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001525 }
1526
Christopher Tatedf01dea2009-06-09 20:45:02 -07001527 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001528 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001529 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001530 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001531 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001532
Christopher Tateb49ceb32010-02-08 16:22:24 -08001533 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001534 int error = -1; // assume error
1535
Dan Egnorefe52642009-06-24 00:16:33 -07001536 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001537 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001538 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001539 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001540
Dan Egnorefe52642009-06-24 00:16:33 -07001541 // Get the list of all packages which have backup enabled.
1542 // (Include the Package Manager metadata pseudo-package first.)
1543 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1544 PackageInfo omPackage = new PackageInfo();
1545 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1546 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001547
Dan Egnorefe52642009-06-24 00:16:33 -07001548 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001549 if (mTargetPackage == null) {
1550 restorePackages.addAll(agentPackages);
1551 } else {
1552 // Just one package to attempt restore of
1553 restorePackages.add(mTargetPackage);
1554 }
Dan Egnorefe52642009-06-24 00:16:33 -07001555
Christopher Tate7d562ec2009-06-25 18:03:43 -07001556 // let the observer know that we're running
1557 if (mObserver != null) {
1558 try {
1559 // !!! TODO: get an actual count from the transport after
1560 // its startRestore() runs?
1561 mObserver.restoreStarting(restorePackages.size());
1562 } catch (RemoteException e) {
1563 Log.d(TAG, "Restore observer died at restoreStarting");
1564 mObserver = null;
1565 }
1566 }
1567
Dan Egnor01445162009-09-21 17:04:05 -07001568 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1569 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001570 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001571 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001572 return;
1573 }
1574
1575 String packageName = mTransport.nextRestorePackage();
1576 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001577 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001579 return;
1580 } else if (packageName.equals("")) {
1581 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001582 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001583 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001584 return;
1585 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1586 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1587 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001588 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001589 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001590 return;
1591 }
1592
1593 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001594 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001595 mPackageManager, agentPackages);
1596 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1597
Christopher Tate8c032472009-07-02 14:28:47 -07001598 // Verify that the backup set includes metadata. If not, we can't do
1599 // signature/version verification etc, so we simply do not proceed with
1600 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001601 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001602 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001603 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001604 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001605 return;
1606 }
1607
Christopher Tate7d562ec2009-06-25 18:03:43 -07001608 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001609 for (;;) {
1610 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001611
Dan Egnorefe52642009-06-24 00:16:33 -07001612 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001613 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001614 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001615 return;
1616 } else if (packageName.equals("")) {
Christopher Tate1bb69062010-02-19 17:02:12 -08001617 if (DEBUG) Log.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001618 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001619 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001620
Christopher Tate7d562ec2009-06-25 18:03:43 -07001621 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001622 try {
1623 mObserver.onUpdate(count);
1624 } catch (RemoteException e) {
1625 Log.d(TAG, "Restore observer died in onUpdate");
1626 mObserver = null;
1627 }
1628 }
1629
Dan Egnorefe52642009-06-24 00:16:33 -07001630 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1631 if (metaInfo == null) {
1632 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001634 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001635 continue;
1636 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001637
Dan Egnorbb9001c2009-07-27 12:20:13 -07001638 PackageInfo packageInfo;
1639 try {
1640 int flags = PackageManager.GET_SIGNATURES;
1641 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1642 } catch (NameNotFoundException e) {
1643 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001644 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001645 "Package missing on device");
1646 continue;
1647 }
1648
Dan Egnorefe52642009-06-24 00:16:33 -07001649 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001650 // Data is from a "newer" version of the app than we have currently
1651 // installed. If the app has not declared that it is prepared to
1652 // handle this case, we do not attempt the restore.
1653 if ((packageInfo.applicationInfo.flags
1654 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1655 String message = "Version " + metaInfo.versionCode
1656 + " > installed version " + packageInfo.versionCode;
1657 Log.w(TAG, "Package " + packageName + ": " + message);
1658 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1659 packageName, message);
1660 continue;
1661 } else {
1662 if (DEBUG) Log.v(TAG, "Version " + metaInfo.versionCode
1663 + " > installed " + packageInfo.versionCode
1664 + " but restoreAnyVersion");
1665 }
Dan Egnorefe52642009-06-24 00:16:33 -07001666 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001667
Christopher Tate78dd4a72009-11-04 11:49:08 -08001668 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001669 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001670 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001671 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001672 continue;
1673 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001674
Dan Egnorefe52642009-06-24 00:16:33 -07001675 if (DEBUG) Log.v(TAG, "Package " + packageName
1676 + " restore version [" + metaInfo.versionCode
1677 + "] is compatible with installed version ["
1678 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001679
Christopher Tate5e1ab332009-09-01 20:32:49 -07001680 // Then set up and bind the agent (with a restricted Application object
1681 // unless the application says otherwise)
1682 boolean useRealApp = (packageInfo.applicationInfo.flags
1683 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1684 if (DEBUG && useRealApp) {
1685 Log.v(TAG, "agent requires real Application subclass for restore");
1686 }
Dan Egnorefe52642009-06-24 00:16:33 -07001687 IBackupAgent agent = bindToAgentSynchronous(
1688 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001689 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1690 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001691 if (agent == null) {
1692 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001693 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001694 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001695 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001696 }
1697
Christopher Tate5e1ab332009-09-01 20:32:49 -07001698 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001699 try {
1700 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001701 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001702 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001703 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001704 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001705
1706 // The agent was probably running with a stub Application object,
1707 // which isn't a valid run mode for the main app logic. Shut
1708 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001709 // usual full initialization. Note that this is only done for
1710 // full-system restores: when a single app has requested a restore,
1711 // it is explicitly not killed following that operation.
1712 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001713 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1714 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1715 + packageInfo.applicationInfo.processName);
1716 mActivityManager.killApplicationProcess(
1717 packageInfo.applicationInfo.processName,
1718 packageInfo.applicationInfo.uid);
1719 }
Dan Egnorefe52642009-06-24 00:16:33 -07001720 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001721 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001722
1723 // if we get this far, report success to the observer
1724 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001725 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001726 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001727 } catch (Exception e) {
1728 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001729 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001730 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1731
Dan Egnorefe52642009-06-24 00:16:33 -07001732 try {
1733 mTransport.finishRestore();
1734 } catch (RemoteException e) {
1735 Log.e(TAG, "Error finishing restore", e);
1736 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001737
1738 if (mObserver != null) {
1739 try {
1740 mObserver.restoreFinished(error);
1741 } catch (RemoteException e) {
1742 Log.d(TAG, "Restore observer died at restoreFinished");
1743 }
1744 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001745
Christopher Tate84725812010-02-04 15:52:40 -08001746 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001747 // ancestral dataset, as well as the set of apps that are possibly
1748 // restoreable from the dataset
1749 if (mTargetPackage == null && pmAgent != null) {
1750 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001751 mAncestralToken = mToken;
1752 writeRestoreTokens();
1753 }
1754
Christopher Tate1bb69062010-02-19 17:02:12 -08001755 // We must under all circumstances tell the Package Manager to
1756 // proceed with install notifications if it's waiting for us.
1757 if (mPmToken > 0) {
1758 if (DEBUG) Log.v(TAG, "finishing PM token " + mPmToken);
1759 try {
1760 mPackageManagerBinder.finishPackageInstall(mPmToken);
1761 } catch (RemoteException e) { /* can't happen */ }
1762 }
1763
Christopher Tateb6787f22009-07-02 17:40:45 -07001764 // done; we can finally release the wakelock
1765 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001766 }
1767 }
1768
Dan Egnorefe52642009-06-24 00:16:33 -07001769 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1770 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001771 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001772 final String packageName = app.packageName;
1773
Dan Egnorbb9001c2009-07-27 12:20:13 -07001774 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001775
Christopher Tatec7b31e32009-06-10 15:49:30 -07001776 // !!! TODO: get the dirs from the transport
1777 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001778 File newStateName = new File(mStateDir, packageName + ".new");
1779 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001780
Dan Egnorbb9001c2009-07-27 12:20:13 -07001781 ParcelFileDescriptor backupData = null;
1782 ParcelFileDescriptor newState = null;
1783
Christopher Tate44a27902010-01-27 17:15:49 -08001784 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001785 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001786 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001787 backupData = ParcelFileDescriptor.open(backupDataName,
1788 ParcelFileDescriptor.MODE_READ_WRITE |
1789 ParcelFileDescriptor.MODE_CREATE |
1790 ParcelFileDescriptor.MODE_TRUNCATE);
1791
Dan Egnor01445162009-09-21 17:04:05 -07001792 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001793 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001795 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001796 }
1797
1798 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001799 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001800 backupData = ParcelFileDescriptor.open(backupDataName,
1801 ParcelFileDescriptor.MODE_READ_ONLY);
1802
Dan Egnorbb9001c2009-07-27 12:20:13 -07001803 newState = ParcelFileDescriptor.open(newStateName,
1804 ParcelFileDescriptor.MODE_READ_WRITE |
1805 ParcelFileDescriptor.MODE_CREATE |
1806 ParcelFileDescriptor.MODE_TRUNCATE);
1807
Christopher Tate44a27902010-01-27 17:15:49 -08001808 // Kick off the restore, checking for hung agents
1809 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1810 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1811 boolean success = waitUntilOperationComplete(token);
1812
1813 if (!success) {
1814 throw new RuntimeException("restore timeout");
1815 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001816
1817 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001818 //
1819 // !!! TODO: the restored data should be migrated on the server
1820 // side into the current dataset. In that case the new state file
1821 // we just created would reflect the data already extant in the
1822 // backend, so there'd be nothing more to do. Until that happens,
1823 // however, we need to make sure that we record the data to the
1824 // current backend dataset. (Yes, this means shipping the data over
1825 // the wire in both directions. That's bad, but consistency comes
1826 // first, then efficiency.) Once we introduce server-side data
1827 // migration to the newly-restored device's dataset, we will change
1828 // the following from a discard of the newly-written state to the
1829 // "correct" operation of renaming into the canonical state blob.
1830 newStateName.delete(); // TODO: remove; see above comment
1831 //newStateName.renameTo(savedStateName); // TODO: replace with this
1832
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001834 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001835 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001836 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001837 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001838
Christopher Tate96733042009-07-20 14:49:13 -07001839 // If the agent fails restore, it might have put the app's data
1840 // into an incoherent state. For consistency we wipe its data
1841 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001842 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001843 } finally {
1844 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001845 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1846 try { if (newState != null) newState.close(); } catch (IOException e) {}
1847 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001848 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001849 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001850 }
1851 }
1852
Christopher Tate44a27902010-01-27 17:15:49 -08001853 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001854 IBackupTransport mTransport;
1855 PackageInfo mPackage;
1856
Christopher Tate44a27902010-01-27 17:15:49 -08001857 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001858 mTransport = transport;
1859 mPackage = packageInfo;
1860 }
1861
Christopher Tateee0e78a2009-07-02 11:17:03 -07001862 public void run() {
1863 try {
1864 // Clear the on-device backup state to ensure a full backup next time
1865 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1866 File stateFile = new File(stateDir, mPackage.packageName);
1867 stateFile.delete();
1868
1869 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001870 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001871 mTransport.clearBackupData(mPackage);
1872 } catch (RemoteException e) {
1873 // can't happen; the transport is local
1874 } finally {
1875 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001876 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001877 mTransport.finishBackup();
1878 } catch (RemoteException e) {
1879 // can't happen; the transport is local
1880 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001881
1882 // Last but not least, release the cpu
1883 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001884 }
1885 }
1886 }
1887
Christopher Tate44a27902010-01-27 17:15:49 -08001888 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001889 HashSet<String> mQueue;
1890
Christopher Tate44a27902010-01-27 17:15:49 -08001891 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001892 mQueue = transportNames;
1893 }
1894
Christopher Tate4cc86e12009-09-21 19:36:51 -07001895 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001896 try {
1897 for (String transportName : mQueue) {
1898 IBackupTransport transport = getTransport(transportName);
1899 if (transport == null) {
1900 Log.e(TAG, "Requested init for " + transportName + " but not found");
1901 continue;
1902 }
1903
Dan Egnor726247c2009-09-29 19:12:31 -07001904 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001905 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001906 long startRealtime = SystemClock.elapsedRealtime();
1907 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001908
Christopher Tate4cc86e12009-09-21 19:36:51 -07001909 if (status == BackupConstants.TRANSPORT_OK) {
1910 status = transport.finishBackup();
1911 }
1912
1913 // Okay, the wipe really happened. Clean up our local bookkeeping.
1914 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001915 Log.i(TAG, "Device init successful");
1916 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001917 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001918 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001919 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001920 synchronized (mQueueLock) {
1921 recordInitPendingLocked(false, transportName);
1922 }
Dan Egnor726247c2009-09-29 19:12:31 -07001923 } else {
1924 // If this didn't work, requeue this one and try again
1925 // after a suitable interval
1926 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001927 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001928 synchronized (mQueueLock) {
1929 recordInitPendingLocked(true, transportName);
1930 }
1931 // do this via another alarm to make sure of the wakelock states
1932 long delay = transport.requestBackupTime();
1933 if (DEBUG) Log.w(TAG, "init failed on "
1934 + transportName + " resched in " + delay);
1935 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1936 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001937 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001938 }
1939 } catch (RemoteException e) {
1940 // can't happen; the transports are local
1941 } catch (Exception e) {
1942 Log.e(TAG, "Unexpected error performing init", e);
1943 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001944 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001945 mWakelock.release();
1946 }
1947 }
1948 }
1949
Christopher Tatedf01dea2009-06-09 20:45:02 -07001950
Christopher Tate487529a2009-04-29 14:03:25 -07001951 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001952
Dan Egnor852f8e42009-09-30 11:20:45 -07001953 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001954 // Record that we need a backup pass for the caller. Since multiple callers
1955 // may share a uid, we need to note all candidates within that uid and schedule
1956 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001957 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001958
Christopher Tate63d27002009-06-16 17:16:42 -07001959 // If the caller does not hold the BACKUP permission, it can only request a
1960 // backup of its own data.
1961 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001962 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001963 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1964 targets = mBackupParticipants.get(Binder.getCallingUid());
1965 } else {
1966 // a caller with full permission can ask to back up any participating app
1967 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001968 targets = new HashSet<ApplicationInfo>();
1969 int N = mBackupParticipants.size();
1970 for (int i = 0; i < N; i++) {
1971 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1972 if (s != null) {
1973 targets.addAll(s);
1974 }
1975 }
1976 }
Christopher Tate487529a2009-04-29 14:03:25 -07001977 if (targets != null) {
1978 synchronized (mQueueLock) {
1979 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001980 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001981 // validate the caller-supplied package name against the known set of
1982 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001983 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001984 // Add the caller to the set of pending backups. If there is
1985 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001986 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001987 if (mPendingBackups.put(app, req) == null) {
1988 // Journal this request in case of crash. The put()
1989 // operation returned null when this package was not already
1990 // in the set; we want to avoid touching the disk redundantly.
1991 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001992
Christopher Tate22b60d82009-07-07 16:36:02 -07001993 if (DEBUG) {
1994 int numKeys = mPendingBackups.size();
1995 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1996 for (BackupRequest b : mPendingBackups.values()) {
1997 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1998 }
1999 }
2000 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002001 }
2002 }
Christopher Tate487529a2009-04-29 14:03:25 -07002003 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002004 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07002005 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2006 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07002007 }
2008 }
Christopher Tate46758122009-05-06 11:22:00 -07002009
Christopher Tatecde87f42009-06-12 12:55:53 -07002010 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002011 RandomAccessFile out = null;
2012 try {
2013 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2014 out = new RandomAccessFile(mJournal, "rws");
2015 out.seek(out.length());
2016 out.writeUTF(str);
2017 } catch (IOException e) {
2018 Log.e(TAG, "Can't write " + str + " to backup journal", e);
2019 mJournal = null;
2020 } finally {
2021 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002022 }
2023 }
2024
Christopher Tateee0e78a2009-07-02 11:17:03 -07002025 // Clear the given package's backup data from the current transport
2026 public void clearBackupData(String packageName) {
2027 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
2028 PackageInfo info;
2029 try {
2030 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2031 } catch (NameNotFoundException e) {
2032 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
2033 return;
2034 }
2035
2036 // If the caller does not hold the BACKUP permission, it can only request a
2037 // wipe of its own backed-up data.
2038 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002039 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002040 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2041 apps = mBackupParticipants.get(Binder.getCallingUid());
2042 } else {
2043 // a caller with full permission can ask to back up any participating app
2044 // !!! TODO: allow data-clear of ANY app?
2045 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
2046 apps = new HashSet<ApplicationInfo>();
2047 int N = mBackupParticipants.size();
2048 for (int i = 0; i < N; i++) {
2049 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2050 if (s != null) {
2051 apps.addAll(s);
2052 }
2053 }
2054 }
2055
2056 // now find the given package in the set of candidate apps
2057 for (ApplicationInfo app : apps) {
2058 if (app.packageName.equals(packageName)) {
2059 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
2060 // found it; fire off the clear request
2061 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002062 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002063 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002064 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2065 new ClearParams(getTransport(mCurrentTransport), info));
2066 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002067 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002068 }
2069 break;
2070 }
2071 }
2072 }
2073
Christopher Tateace7f092009-06-15 18:07:25 -07002074 // Run a backup pass immediately for any applications that have declared
2075 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002076 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002077 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002078
Christopher Tateace7f092009-06-15 18:07:25 -07002079 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002080 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002081 // Because the alarms we are using can jitter, and we want an *immediate*
2082 // backup pass to happen, we restart the timer beginning with "next time,"
2083 // then manually fire the backup trigger intent ourselves.
2084 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002085 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002086 mRunBackupIntent.send();
2087 } catch (PendingIntent.CanceledException e) {
2088 // should never happen
2089 Log.e(TAG, "run-backup intent cancelled!");
2090 }
Christopher Tate46758122009-05-06 11:22:00 -07002091 }
2092 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002093
Christopher Tate8031a3d2009-07-06 16:36:05 -07002094 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002095 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2097 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002098
Christopher Tate4cc86e12009-09-21 19:36:51 -07002099 Log.i(TAG, "Backup enabled => " + enable);
2100
Christopher Tate6ef58a12009-06-29 14:56:28 -07002101 boolean wasEnabled = mEnabled;
2102 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002103 Settings.Secure.putInt(mContext.getContentResolver(),
2104 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002105 mEnabled = enable;
2106 }
2107
Christopher Tate49401dd2009-07-01 12:34:29 -07002108 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002109 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002110 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002111 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002112 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002113 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002114 if (DEBUG) Log.i(TAG, "Opting out of backup");
2115
Christopher Tateb6787f22009-07-02 17:40:45 -07002116 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002117
2118 // This also constitutes an opt-out, so we wipe any data for
2119 // this device from the backend. We start that process with
2120 // an alarm in order to guarantee wakelock states.
2121 if (wasEnabled && mProvisioned) {
2122 // NOTE: we currently flush every registered transport, not just
2123 // the currently-active one.
2124 HashSet<String> allTransports;
2125 synchronized (mTransports) {
2126 allTransports = new HashSet<String>(mTransports.keySet());
2127 }
2128 // build the set of transports for which we are posting an init
2129 for (String transport : allTransports) {
2130 recordInitPendingLocked(true, transport);
2131 }
2132 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2133 mRunInitIntent);
2134 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002135 }
2136 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002137 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002138
Christopher Tatecce9da52010-02-03 15:11:15 -08002139 // Enable/disable automatic restore of app data at install time
2140 public void setAutoRestore(boolean doAutoRestore) {
2141 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2142 "setBackupEnabled");
2143
2144 Log.i(TAG, "Auto restore => " + doAutoRestore);
2145
2146 synchronized (this) {
2147 Settings.Secure.putInt(mContext.getContentResolver(),
2148 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2149 mAutoRestore = doAutoRestore;
2150 }
2151 }
2152
Christopher Tate8031a3d2009-07-06 16:36:05 -07002153 // Mark the backup service as having been provisioned
2154 public void setBackupProvisioned(boolean available) {
2155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2156 "setBackupProvisioned");
2157
2158 boolean wasProvisioned = mProvisioned;
2159 synchronized (this) {
2160 Settings.Secure.putInt(mContext.getContentResolver(),
2161 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2162 mProvisioned = available;
2163 }
2164
2165 synchronized (mQueueLock) {
2166 if (available && !wasProvisioned && mEnabled) {
2167 // we're now good to go, so start the backup alarms
2168 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2169 } else if (!available) {
2170 // No longer enabled, so stop running backups
2171 Log.w(TAG, "Backup service no longer provisioned");
2172 mAlarmManager.cancel(mRunBackupIntent);
2173 }
2174 }
2175 }
2176
2177 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002178 // We used to use setInexactRepeating(), but that may be linked to
2179 // backups running at :00 more often than not, creating load spikes.
2180 // Schedule at an exact time for now, and also add a bit of "fuzz".
2181
2182 Random random = new Random();
2183 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2184 random.nextInt(FUZZ_MILLIS);
2185 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2186 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002187 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002188 }
2189
Christopher Tate6ef58a12009-06-29 14:56:28 -07002190 // Report whether the backup mechanism is currently enabled
2191 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002192 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002193 return mEnabled; // no need to synchronize just to read it
2194 }
2195
Christopher Tate91717492009-06-26 21:07:13 -07002196 // Report the name of the currently active transport
2197 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002198 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002199 "getCurrentTransport");
Christopher Tate1bb69062010-02-19 17:02:12 -08002200 if (DEBUG) Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002201 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002202 }
2203
Christopher Tate91717492009-06-26 21:07:13 -07002204 // Report all known, available backup transports
2205 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002207
Christopher Tate91717492009-06-26 21:07:13 -07002208 String[] list = null;
2209 ArrayList<String> known = new ArrayList<String>();
2210 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2211 if (entry.getValue() != null) {
2212 known.add(entry.getKey());
2213 }
2214 }
2215
2216 if (known.size() > 0) {
2217 list = new String[known.size()];
2218 known.toArray(list);
2219 }
2220 return list;
2221 }
2222
2223 // Select which transport to use for the next backup operation. If the given
2224 // name is not one of the available transports, no action is taken and the method
2225 // returns null.
2226 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002228
2229 synchronized (mTransports) {
2230 String prevTransport = null;
2231 if (mTransports.get(transport) != null) {
2232 prevTransport = mCurrentTransport;
2233 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002234 Settings.Secure.putString(mContext.getContentResolver(),
2235 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002236 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2237 + " returning " + prevTransport);
2238 } else {
2239 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2240 }
2241 return prevTransport;
2242 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002243 }
2244
2245 // Callback: a requested backup agent has been instantiated. This should only
2246 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002247 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002248 synchronized(mAgentConnectLock) {
2249 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2250 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2251 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2252 mConnectedAgent = agent;
2253 mConnecting = false;
2254 } else {
2255 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2256 + " claiming agent connected");
2257 }
2258 mAgentConnectLock.notifyAll();
2259 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002260 }
2261
2262 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2263 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002264 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002265 public void agentDisconnected(String packageName) {
2266 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002267 synchronized(mAgentConnectLock) {
2268 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2269 mConnectedAgent = null;
2270 mConnecting = false;
2271 } else {
2272 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2273 + " claiming agent disconnected");
2274 }
2275 mAgentConnectLock.notifyAll();
2276 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002277 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002278
Christopher Tate1bb69062010-02-19 17:02:12 -08002279 // An application being installed will need a restore pass, then the Package Manager
2280 // will need to be told when the restore is finished.
2281 public void restoreAtInstall(String packageName, int token) {
2282 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2283 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2284 + " attemping install-time restore");
2285 return;
2286 }
2287
2288 long restoreSet = getAvailableRestoreToken(packageName);
2289 if (DEBUG) Log.v(TAG, "restoreAtInstall pkg=" + packageName
2290 + " token=" + Integer.toHexString(token));
2291
Christopher Tatef0872722010-02-25 15:22:48 -08002292 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002293 // okay, we're going to attempt a restore of this package from this restore set.
2294 // The eventual message back into the Package Manager to run the post-install
2295 // steps for 'token' will be issued from the restore handling code.
2296
2297 // We can use a synthetic PackageInfo here because:
2298 // 1. We know it's valid, since the Package Manager supplied the name
2299 // 2. Only the packageName field will be used by the restore code
2300 PackageInfo pkg = new PackageInfo();
2301 pkg.packageName = packageName;
2302
2303 mWakelock.acquire();
2304 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2305 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2306 restoreSet, pkg, token);
2307 mBackupHandler.sendMessage(msg);
2308 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002309 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2310 // Manager to proceed with the post-install handling for this package.
Christopher Tate1bb69062010-02-19 17:02:12 -08002311 if (DEBUG) Log.v(TAG, "No restore set -- skipping restore");
2312 try {
2313 mPackageManagerBinder.finishPackageInstall(token);
2314 } catch (RemoteException e) { /* can't happen */ }
2315 }
2316 }
2317
Christopher Tate8c850b72009-06-07 19:33:20 -07002318 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002319 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002320 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002321
2322 synchronized(this) {
2323 if (mActiveRestoreSession != null) {
2324 Log.d(TAG, "Restore session requested but one already active");
2325 return null;
2326 }
Christopher Tate80202c82010-01-25 19:37:47 -08002327 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002328 }
2329 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002330 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002331
Christopher Tate44a27902010-01-27 17:15:49 -08002332 // Note that a currently-active backup agent has notified us that it has
2333 // completed the given outstanding asynchronous backup/restore operation.
2334 public void opComplete(int token) {
2335 synchronized (mCurrentOpLock) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002336 if (DEBUG) Log.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002337 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2338 mCurrentOpLock.notifyAll();
2339 }
2340 }
2341
Christopher Tate9b3905c2009-06-08 15:24:01 -07002342 // ----- Restore session -----
2343
Christopher Tate80202c82010-01-25 19:37:47 -08002344 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002345 private static final String TAG = "RestoreSession";
2346
Christopher Tate9b3905c2009-06-08 15:24:01 -07002347 private IBackupTransport mRestoreTransport = null;
2348 RestoreSet[] mRestoreSets = null;
2349
Christopher Tate80202c82010-01-25 19:37:47 -08002350 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002351 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002352 }
2353
2354 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002355 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002357 "getAvailableRestoreSets");
2358
Christopher Tate1bb69062010-02-19 17:02:12 -08002359 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002360 try {
Christopher Tate43383042009-07-13 15:17:13 -07002361 if (mRestoreTransport == null) {
2362 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002363 return null;
2364 }
2365 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002366 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002367 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002368 }
2369 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002370 } catch (Exception e) {
2371 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2372 return null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002373 } finally {
2374 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002375 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002376 }
2377
Christopher Tate84725812010-02-04 15:52:40 -08002378 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2380 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002381
Christopher Tatef2c321a2009-08-10 15:43:36 -07002382 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2383 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002384
Dan Egnor0084da52009-07-29 12:57:16 -07002385 if (mRestoreTransport == null || mRestoreSets == null) {
2386 Log.e(TAG, "Ignoring performRestore() with no restore set");
2387 return -1;
2388 }
2389
Christopher Tate21ab6a52009-09-24 18:01:46 -07002390 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002391 for (int i = 0; i < mRestoreSets.length; i++) {
2392 if (token == mRestoreSets[i].token) {
2393 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002394 mWakelock.acquire();
2395 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2396 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2397 mBackupHandler.sendMessage(msg);
2398 Binder.restoreCallingIdentity(oldId);
2399 return 0;
2400 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002401 }
2402 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002403
2404 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002405 return -1;
2406 }
2407
Christopher Tate84725812010-02-04 15:52:40 -08002408 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
2409 if (DEBUG) Log.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
2410
2411 PackageInfo app = null;
2412 try {
2413 app = mPackageManager.getPackageInfo(packageName, 0);
2414 } catch (NameNotFoundException nnf) {
2415 Log.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2416 return -1;
2417 }
2418
2419 // If the caller is not privileged and is not coming from the target
2420 // app's uid, throw a permission exception back to the caller.
2421 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2422 Binder.getCallingPid(), Binder.getCallingUid());
2423 if ((perm == PackageManager.PERMISSION_DENIED) &&
2424 (app.applicationInfo.uid != Binder.getCallingUid())) {
2425 Log.w(TAG, "restorePackage: bad packageName=" + packageName
2426 + " or calling uid=" + Binder.getCallingUid());
2427 throw new SecurityException("No permission to restore other packages");
2428 }
2429
Christopher Tate7d411a32010-02-26 11:27:08 -08002430 // If the package has no backup agent, we obviously cannot proceed
2431 if (app.applicationInfo.backupAgentName == null) {
2432 Log.w(TAG, "Asked to restore package " + packageName + " with no agent");
2433 return -1;
2434 }
2435
Christopher Tate84725812010-02-04 15:52:40 -08002436 // So far so good; we're allowed to try to restore this package. Now
2437 // check whether there is data for it in the current dataset, falling back
2438 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002439 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002440
2441 // If we didn't come up with a place to look -- no ancestral dataset and
2442 // the app has never been backed up from this device -- there's nothing
2443 // to do but return failure.
2444 if (token == 0) {
2445 return -1;
2446 }
2447
2448 // Ready to go: enqueue the restore request and claim success
2449 long oldId = Binder.clearCallingIdentity();
2450 mWakelock.acquire();
2451 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002452 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002453 mBackupHandler.sendMessage(msg);
2454 Binder.restoreCallingIdentity(oldId);
2455 return 0;
2456 }
2457
Dan Egnor0084da52009-07-29 12:57:16 -07002458 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002460 "endRestoreSession");
2461
Dan Egnor0084da52009-07-29 12:57:16 -07002462 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002463
Dan Egnor0084da52009-07-29 12:57:16 -07002464 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002465 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002466 try {
2467 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2468 } catch (Exception e) {
2469 Log.e(TAG, "Error in finishRestore", e);
2470 } finally {
2471 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002472 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002473 }
2474 }
2475
2476 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002477 if (BackupManagerService.this.mActiveRestoreSession == this) {
2478 BackupManagerService.this.mActiveRestoreSession = null;
2479 } else {
2480 Log.e(TAG, "ending non-current restore session");
2481 }
2482 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002483 }
2484 }
2485
Christopher Tate043dadc2009-06-02 16:11:00 -07002486
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002487 @Override
2488 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2489 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002490 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002491 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002492 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002493 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002494 pw.println("Last backup pass: " + mLastBackupPass
2495 + " (now = " + System.currentTimeMillis() + ')');
2496 pw.println(" next scheduled: " + mNextBackupPass);
2497
Christopher Tate91717492009-06-26 21:07:13 -07002498 pw.println("Available transports:");
2499 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002500 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2501 try {
2502 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2503 for (File f : dir.listFiles()) {
2504 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2505 }
2506 } catch (RemoteException e) {
2507 Log.e(TAG, "Error in transportDirName()", e);
2508 pw.println(" Error: " + e);
2509 }
Christopher Tate91717492009-06-26 21:07:13 -07002510 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002511
2512 pw.println("Pending init: " + mPendingInits.size());
2513 for (String s : mPendingInits) {
2514 pw.println(" " + s);
2515 }
2516
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002517 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002518 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002519 for (int i=0; i<N; i++) {
2520 int uid = mBackupParticipants.keyAt(i);
2521 pw.print(" uid: ");
2522 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002523 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2524 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002525 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002526 }
2527 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002528
Christopher Tateb49ceb32010-02-08 16:22:24 -08002529 pw.println("Ancestral packages: "
2530 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
2531 for (String pkg : mAncestralPackages) {
2532 pw.println(" " + pkg);
2533 }
2534
Christopher Tate73e02522009-07-15 14:18:26 -07002535 pw.println("Ever backed up: " + mEverStoredApps.size());
2536 for (String pkg : mEverStoredApps) {
2537 pw.println(" " + pkg);
2538 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002539
2540 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002541 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002542 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002543 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002544 }
2545 }
Christopher Tate487529a2009-04-29 14:03:25 -07002546}