blob: f79a02a9166e8706743eb7d2f64c11f066055a8e [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(),
377 Settings.Secure.BACKUP_AUTO_RESTORE, 0) != 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) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001650 String message = "Version " + metaInfo.versionCode
1651 + " > installed version " + packageInfo.versionCode;
1652 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001654 continue;
1655 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001656
Christopher Tate78dd4a72009-11-04 11:49:08 -08001657 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001658 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001659 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001660 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001661 continue;
1662 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001663
Dan Egnorefe52642009-06-24 00:16:33 -07001664 if (DEBUG) Log.v(TAG, "Package " + packageName
1665 + " restore version [" + metaInfo.versionCode
1666 + "] is compatible with installed version ["
1667 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001668
Christopher Tate5e1ab332009-09-01 20:32:49 -07001669 // Then set up and bind the agent (with a restricted Application object
1670 // unless the application says otherwise)
1671 boolean useRealApp = (packageInfo.applicationInfo.flags
1672 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1673 if (DEBUG && useRealApp) {
1674 Log.v(TAG, "agent requires real Application subclass for restore");
1675 }
Dan Egnorefe52642009-06-24 00:16:33 -07001676 IBackupAgent agent = bindToAgentSynchronous(
1677 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001678 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1679 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001680 if (agent == null) {
1681 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001682 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001683 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001684 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001685 }
1686
Christopher Tate5e1ab332009-09-01 20:32:49 -07001687 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001688 try {
1689 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001690 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001691 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001692 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001693 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001694
1695 // The agent was probably running with a stub Application object,
1696 // which isn't a valid run mode for the main app logic. Shut
1697 // down the app so that next time it's launched, it gets the
1698 // usual full initialization.
1699 if ((packageInfo.applicationInfo.flags
1700 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1701 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1702 + packageInfo.applicationInfo.processName);
1703 mActivityManager.killApplicationProcess(
1704 packageInfo.applicationInfo.processName,
1705 packageInfo.applicationInfo.uid);
1706 }
Dan Egnorefe52642009-06-24 00:16:33 -07001707 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001708 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001709
1710 // if we get this far, report success to the observer
1711 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001712 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001713 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001714 } catch (Exception e) {
1715 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001716 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001717 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1718
Dan Egnorefe52642009-06-24 00:16:33 -07001719 try {
1720 mTransport.finishRestore();
1721 } catch (RemoteException e) {
1722 Log.e(TAG, "Error finishing restore", e);
1723 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001724
1725 if (mObserver != null) {
1726 try {
1727 mObserver.restoreFinished(error);
1728 } catch (RemoteException e) {
1729 Log.d(TAG, "Restore observer died at restoreFinished");
1730 }
1731 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001732
Christopher Tate84725812010-02-04 15:52:40 -08001733 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001734 // ancestral dataset, as well as the set of apps that are possibly
1735 // restoreable from the dataset
1736 if (mTargetPackage == null && pmAgent != null) {
1737 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001738 mAncestralToken = mToken;
1739 writeRestoreTokens();
1740 }
1741
Christopher Tate1bb69062010-02-19 17:02:12 -08001742 // We must under all circumstances tell the Package Manager to
1743 // proceed with install notifications if it's waiting for us.
1744 if (mPmToken > 0) {
1745 if (DEBUG) Log.v(TAG, "finishing PM token " + mPmToken);
1746 try {
1747 mPackageManagerBinder.finishPackageInstall(mPmToken);
1748 } catch (RemoteException e) { /* can't happen */ }
1749 }
1750
Christopher Tateb6787f22009-07-02 17:40:45 -07001751 // done; we can finally release the wakelock
1752 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001753 }
1754 }
1755
Dan Egnorefe52642009-06-24 00:16:33 -07001756 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1757 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001758 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001759 final String packageName = app.packageName;
1760
Dan Egnorbb9001c2009-07-27 12:20:13 -07001761 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001762
Christopher Tatec7b31e32009-06-10 15:49:30 -07001763 // !!! TODO: get the dirs from the transport
1764 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001765 File newStateName = new File(mStateDir, packageName + ".new");
1766 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001767
Dan Egnorbb9001c2009-07-27 12:20:13 -07001768 ParcelFileDescriptor backupData = null;
1769 ParcelFileDescriptor newState = null;
1770
Christopher Tate44a27902010-01-27 17:15:49 -08001771 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001772 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001773 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001774 backupData = ParcelFileDescriptor.open(backupDataName,
1775 ParcelFileDescriptor.MODE_READ_WRITE |
1776 ParcelFileDescriptor.MODE_CREATE |
1777 ParcelFileDescriptor.MODE_TRUNCATE);
1778
Dan Egnor01445162009-09-21 17:04:05 -07001779 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001780 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001781 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001782 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001783 }
1784
1785 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001786 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001787 backupData = ParcelFileDescriptor.open(backupDataName,
1788 ParcelFileDescriptor.MODE_READ_ONLY);
1789
Dan Egnorbb9001c2009-07-27 12:20:13 -07001790 newState = ParcelFileDescriptor.open(newStateName,
1791 ParcelFileDescriptor.MODE_READ_WRITE |
1792 ParcelFileDescriptor.MODE_CREATE |
1793 ParcelFileDescriptor.MODE_TRUNCATE);
1794
Christopher Tate44a27902010-01-27 17:15:49 -08001795 // Kick off the restore, checking for hung agents
1796 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1797 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1798 boolean success = waitUntilOperationComplete(token);
1799
1800 if (!success) {
1801 throw new RuntimeException("restore timeout");
1802 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001803
1804 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001805 //
1806 // !!! TODO: the restored data should be migrated on the server
1807 // side into the current dataset. In that case the new state file
1808 // we just created would reflect the data already extant in the
1809 // backend, so there'd be nothing more to do. Until that happens,
1810 // however, we need to make sure that we record the data to the
1811 // current backend dataset. (Yes, this means shipping the data over
1812 // the wire in both directions. That's bad, but consistency comes
1813 // first, then efficiency.) Once we introduce server-side data
1814 // migration to the newly-restored device's dataset, we will change
1815 // the following from a discard of the newly-written state to the
1816 // "correct" operation of renaming into the canonical state blob.
1817 newStateName.delete(); // TODO: remove; see above comment
1818 //newStateName.renameTo(savedStateName); // TODO: replace with this
1819
Dan Egnorbb9001c2009-07-27 12:20:13 -07001820 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001821 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001822 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001823 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001824 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001825
Christopher Tate96733042009-07-20 14:49:13 -07001826 // If the agent fails restore, it might have put the app's data
1827 // into an incoherent state. For consistency we wipe its data
1828 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001829 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001830 } finally {
1831 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001832 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1833 try { if (newState != null) newState.close(); } catch (IOException e) {}
1834 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001835 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001836 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001837 }
1838 }
1839
Christopher Tate44a27902010-01-27 17:15:49 -08001840 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001841 IBackupTransport mTransport;
1842 PackageInfo mPackage;
1843
Christopher Tate44a27902010-01-27 17:15:49 -08001844 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001845 mTransport = transport;
1846 mPackage = packageInfo;
1847 }
1848
Christopher Tateee0e78a2009-07-02 11:17:03 -07001849 public void run() {
1850 try {
1851 // Clear the on-device backup state to ensure a full backup next time
1852 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1853 File stateFile = new File(stateDir, mPackage.packageName);
1854 stateFile.delete();
1855
1856 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001857 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001858 mTransport.clearBackupData(mPackage);
1859 } catch (RemoteException e) {
1860 // can't happen; the transport is local
1861 } finally {
1862 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001863 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001864 mTransport.finishBackup();
1865 } catch (RemoteException e) {
1866 // can't happen; the transport is local
1867 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001868
1869 // Last but not least, release the cpu
1870 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001871 }
1872 }
1873 }
1874
Christopher Tate44a27902010-01-27 17:15:49 -08001875 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001876 HashSet<String> mQueue;
1877
Christopher Tate44a27902010-01-27 17:15:49 -08001878 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001879 mQueue = transportNames;
1880 }
1881
Christopher Tate4cc86e12009-09-21 19:36:51 -07001882 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001883 try {
1884 for (String transportName : mQueue) {
1885 IBackupTransport transport = getTransport(transportName);
1886 if (transport == null) {
1887 Log.e(TAG, "Requested init for " + transportName + " but not found");
1888 continue;
1889 }
1890
Dan Egnor726247c2009-09-29 19:12:31 -07001891 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001892 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001893 long startRealtime = SystemClock.elapsedRealtime();
1894 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001895
Christopher Tate4cc86e12009-09-21 19:36:51 -07001896 if (status == BackupConstants.TRANSPORT_OK) {
1897 status = transport.finishBackup();
1898 }
1899
1900 // Okay, the wipe really happened. Clean up our local bookkeeping.
1901 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001902 Log.i(TAG, "Device init successful");
1903 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001904 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001905 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001907 synchronized (mQueueLock) {
1908 recordInitPendingLocked(false, transportName);
1909 }
Dan Egnor726247c2009-09-29 19:12:31 -07001910 } else {
1911 // If this didn't work, requeue this one and try again
1912 // after a suitable interval
1913 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001914 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001915 synchronized (mQueueLock) {
1916 recordInitPendingLocked(true, transportName);
1917 }
1918 // do this via another alarm to make sure of the wakelock states
1919 long delay = transport.requestBackupTime();
1920 if (DEBUG) Log.w(TAG, "init failed on "
1921 + transportName + " resched in " + delay);
1922 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1923 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001924 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001925 }
1926 } catch (RemoteException e) {
1927 // can't happen; the transports are local
1928 } catch (Exception e) {
1929 Log.e(TAG, "Unexpected error performing init", e);
1930 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001931 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001932 mWakelock.release();
1933 }
1934 }
1935 }
1936
Christopher Tatedf01dea2009-06-09 20:45:02 -07001937
Christopher Tate487529a2009-04-29 14:03:25 -07001938 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001939
Dan Egnor852f8e42009-09-30 11:20:45 -07001940 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001941 // Record that we need a backup pass for the caller. Since multiple callers
1942 // may share a uid, we need to note all candidates within that uid and schedule
1943 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001944 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001945
Christopher Tate63d27002009-06-16 17:16:42 -07001946 // If the caller does not hold the BACKUP permission, it can only request a
1947 // backup of its own data.
1948 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001949 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001950 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1951 targets = mBackupParticipants.get(Binder.getCallingUid());
1952 } else {
1953 // a caller with full permission can ask to back up any participating app
1954 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001955 targets = new HashSet<ApplicationInfo>();
1956 int N = mBackupParticipants.size();
1957 for (int i = 0; i < N; i++) {
1958 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1959 if (s != null) {
1960 targets.addAll(s);
1961 }
1962 }
1963 }
Christopher Tate487529a2009-04-29 14:03:25 -07001964 if (targets != null) {
1965 synchronized (mQueueLock) {
1966 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001967 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001968 // validate the caller-supplied package name against the known set of
1969 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001970 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001971 // Add the caller to the set of pending backups. If there is
1972 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001973 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001974 if (mPendingBackups.put(app, req) == null) {
1975 // Journal this request in case of crash. The put()
1976 // operation returned null when this package was not already
1977 // in the set; we want to avoid touching the disk redundantly.
1978 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001979
Christopher Tate22b60d82009-07-07 16:36:02 -07001980 if (DEBUG) {
1981 int numKeys = mPendingBackups.size();
1982 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1983 for (BackupRequest b : mPendingBackups.values()) {
1984 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1985 }
1986 }
1987 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001988 }
1989 }
Christopher Tate487529a2009-04-29 14:03:25 -07001990 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001991 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001992 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1993 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001994 }
1995 }
Christopher Tate46758122009-05-06 11:22:00 -07001996
Christopher Tatecde87f42009-06-12 12:55:53 -07001997 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001998 RandomAccessFile out = null;
1999 try {
2000 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2001 out = new RandomAccessFile(mJournal, "rws");
2002 out.seek(out.length());
2003 out.writeUTF(str);
2004 } catch (IOException e) {
2005 Log.e(TAG, "Can't write " + str + " to backup journal", e);
2006 mJournal = null;
2007 } finally {
2008 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002009 }
2010 }
2011
Christopher Tateee0e78a2009-07-02 11:17:03 -07002012 // Clear the given package's backup data from the current transport
2013 public void clearBackupData(String packageName) {
2014 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
2015 PackageInfo info;
2016 try {
2017 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2018 } catch (NameNotFoundException e) {
2019 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
2020 return;
2021 }
2022
2023 // If the caller does not hold the BACKUP permission, it can only request a
2024 // wipe of its own backed-up data.
2025 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002026 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002027 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2028 apps = mBackupParticipants.get(Binder.getCallingUid());
2029 } else {
2030 // a caller with full permission can ask to back up any participating app
2031 // !!! TODO: allow data-clear of ANY app?
2032 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
2033 apps = new HashSet<ApplicationInfo>();
2034 int N = mBackupParticipants.size();
2035 for (int i = 0; i < N; i++) {
2036 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2037 if (s != null) {
2038 apps.addAll(s);
2039 }
2040 }
2041 }
2042
2043 // now find the given package in the set of candidate apps
2044 for (ApplicationInfo app : apps) {
2045 if (app.packageName.equals(packageName)) {
2046 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
2047 // found it; fire off the clear request
2048 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002049 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002050 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002051 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2052 new ClearParams(getTransport(mCurrentTransport), info));
2053 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002054 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002055 }
2056 break;
2057 }
2058 }
2059 }
2060
Christopher Tateace7f092009-06-15 18:07:25 -07002061 // Run a backup pass immediately for any applications that have declared
2062 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002063 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002064 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002065
Christopher Tateace7f092009-06-15 18:07:25 -07002066 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002067 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002068 // Because the alarms we are using can jitter, and we want an *immediate*
2069 // backup pass to happen, we restart the timer beginning with "next time,"
2070 // then manually fire the backup trigger intent ourselves.
2071 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002072 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002073 mRunBackupIntent.send();
2074 } catch (PendingIntent.CanceledException e) {
2075 // should never happen
2076 Log.e(TAG, "run-backup intent cancelled!");
2077 }
Christopher Tate46758122009-05-06 11:22:00 -07002078 }
2079 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002080
Christopher Tate8031a3d2009-07-06 16:36:05 -07002081 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002082 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2084 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002085
Christopher Tate4cc86e12009-09-21 19:36:51 -07002086 Log.i(TAG, "Backup enabled => " + enable);
2087
Christopher Tate6ef58a12009-06-29 14:56:28 -07002088 boolean wasEnabled = mEnabled;
2089 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002090 Settings.Secure.putInt(mContext.getContentResolver(),
2091 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002092 mEnabled = enable;
2093 }
2094
Christopher Tate49401dd2009-07-01 12:34:29 -07002095 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002096 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002097 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002098 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002099 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002100 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002101 if (DEBUG) Log.i(TAG, "Opting out of backup");
2102
Christopher Tateb6787f22009-07-02 17:40:45 -07002103 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002104
2105 // This also constitutes an opt-out, so we wipe any data for
2106 // this device from the backend. We start that process with
2107 // an alarm in order to guarantee wakelock states.
2108 if (wasEnabled && mProvisioned) {
2109 // NOTE: we currently flush every registered transport, not just
2110 // the currently-active one.
2111 HashSet<String> allTransports;
2112 synchronized (mTransports) {
2113 allTransports = new HashSet<String>(mTransports.keySet());
2114 }
2115 // build the set of transports for which we are posting an init
2116 for (String transport : allTransports) {
2117 recordInitPendingLocked(true, transport);
2118 }
2119 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2120 mRunInitIntent);
2121 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002122 }
2123 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002124 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002125
Christopher Tatecce9da52010-02-03 15:11:15 -08002126 // Enable/disable automatic restore of app data at install time
2127 public void setAutoRestore(boolean doAutoRestore) {
2128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2129 "setBackupEnabled");
2130
2131 Log.i(TAG, "Auto restore => " + doAutoRestore);
2132
2133 synchronized (this) {
2134 Settings.Secure.putInt(mContext.getContentResolver(),
2135 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2136 mAutoRestore = doAutoRestore;
2137 }
2138 }
2139
Christopher Tate8031a3d2009-07-06 16:36:05 -07002140 // Mark the backup service as having been provisioned
2141 public void setBackupProvisioned(boolean available) {
2142 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2143 "setBackupProvisioned");
2144
2145 boolean wasProvisioned = mProvisioned;
2146 synchronized (this) {
2147 Settings.Secure.putInt(mContext.getContentResolver(),
2148 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2149 mProvisioned = available;
2150 }
2151
2152 synchronized (mQueueLock) {
2153 if (available && !wasProvisioned && mEnabled) {
2154 // we're now good to go, so start the backup alarms
2155 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2156 } else if (!available) {
2157 // No longer enabled, so stop running backups
2158 Log.w(TAG, "Backup service no longer provisioned");
2159 mAlarmManager.cancel(mRunBackupIntent);
2160 }
2161 }
2162 }
2163
2164 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002165 // We used to use setInexactRepeating(), but that may be linked to
2166 // backups running at :00 more often than not, creating load spikes.
2167 // Schedule at an exact time for now, and also add a bit of "fuzz".
2168
2169 Random random = new Random();
2170 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2171 random.nextInt(FUZZ_MILLIS);
2172 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2173 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002174 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002175 }
2176
Christopher Tate6ef58a12009-06-29 14:56:28 -07002177 // Report whether the backup mechanism is currently enabled
2178 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002180 return mEnabled; // no need to synchronize just to read it
2181 }
2182
Christopher Tate91717492009-06-26 21:07:13 -07002183 // Report the name of the currently active transport
2184 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002185 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002186 "getCurrentTransport");
Christopher Tate1bb69062010-02-19 17:02:12 -08002187 if (DEBUG) Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002188 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002189 }
2190
Christopher Tate91717492009-06-26 21:07:13 -07002191 // Report all known, available backup transports
2192 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002193 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002194
Christopher Tate91717492009-06-26 21:07:13 -07002195 String[] list = null;
2196 ArrayList<String> known = new ArrayList<String>();
2197 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2198 if (entry.getValue() != null) {
2199 known.add(entry.getKey());
2200 }
2201 }
2202
2203 if (known.size() > 0) {
2204 list = new String[known.size()];
2205 known.toArray(list);
2206 }
2207 return list;
2208 }
2209
2210 // Select which transport to use for the next backup operation. If the given
2211 // name is not one of the available transports, no action is taken and the method
2212 // returns null.
2213 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002214 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002215
2216 synchronized (mTransports) {
2217 String prevTransport = null;
2218 if (mTransports.get(transport) != null) {
2219 prevTransport = mCurrentTransport;
2220 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002221 Settings.Secure.putString(mContext.getContentResolver(),
2222 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002223 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2224 + " returning " + prevTransport);
2225 } else {
2226 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2227 }
2228 return prevTransport;
2229 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002230 }
2231
2232 // Callback: a requested backup agent has been instantiated. This should only
2233 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002234 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002235 synchronized(mAgentConnectLock) {
2236 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2237 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2238 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2239 mConnectedAgent = agent;
2240 mConnecting = false;
2241 } else {
2242 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2243 + " claiming agent connected");
2244 }
2245 mAgentConnectLock.notifyAll();
2246 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002247 }
2248
2249 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2250 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002251 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002252 public void agentDisconnected(String packageName) {
2253 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002254 synchronized(mAgentConnectLock) {
2255 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2256 mConnectedAgent = null;
2257 mConnecting = false;
2258 } else {
2259 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2260 + " claiming agent disconnected");
2261 }
2262 mAgentConnectLock.notifyAll();
2263 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002264 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002265
Christopher Tate1bb69062010-02-19 17:02:12 -08002266 // An application being installed will need a restore pass, then the Package Manager
2267 // will need to be told when the restore is finished.
2268 public void restoreAtInstall(String packageName, int token) {
2269 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2270 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2271 + " attemping install-time restore");
2272 return;
2273 }
2274
2275 long restoreSet = getAvailableRestoreToken(packageName);
2276 if (DEBUG) Log.v(TAG, "restoreAtInstall pkg=" + packageName
2277 + " token=" + Integer.toHexString(token));
2278
2279 if (restoreSet != 0) {
2280 // okay, we're going to attempt a restore of this package from this restore set.
2281 // The eventual message back into the Package Manager to run the post-install
2282 // steps for 'token' will be issued from the restore handling code.
2283
2284 // We can use a synthetic PackageInfo here because:
2285 // 1. We know it's valid, since the Package Manager supplied the name
2286 // 2. Only the packageName field will be used by the restore code
2287 PackageInfo pkg = new PackageInfo();
2288 pkg.packageName = packageName;
2289
2290 mWakelock.acquire();
2291 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2292 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2293 restoreSet, pkg, token);
2294 mBackupHandler.sendMessage(msg);
2295 } else {
2296 // No way to attempt a restore; just tell the Package Manager to proceed
2297 // with the post-install handling for this package.
2298 if (DEBUG) Log.v(TAG, "No restore set -- skipping restore");
2299 try {
2300 mPackageManagerBinder.finishPackageInstall(token);
2301 } catch (RemoteException e) { /* can't happen */ }
2302 }
2303 }
2304
Christopher Tate8c850b72009-06-07 19:33:20 -07002305 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002306 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002308
2309 synchronized(this) {
2310 if (mActiveRestoreSession != null) {
2311 Log.d(TAG, "Restore session requested but one already active");
2312 return null;
2313 }
Christopher Tate80202c82010-01-25 19:37:47 -08002314 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002315 }
2316 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002317 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002318
Christopher Tate44a27902010-01-27 17:15:49 -08002319 // Note that a currently-active backup agent has notified us that it has
2320 // completed the given outstanding asynchronous backup/restore operation.
2321 public void opComplete(int token) {
2322 synchronized (mCurrentOpLock) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002323 if (DEBUG) Log.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002324 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2325 mCurrentOpLock.notifyAll();
2326 }
2327 }
2328
Christopher Tate9b3905c2009-06-08 15:24:01 -07002329 // ----- Restore session -----
2330
Christopher Tate80202c82010-01-25 19:37:47 -08002331 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002332 private static final String TAG = "RestoreSession";
2333
Christopher Tate9b3905c2009-06-08 15:24:01 -07002334 private IBackupTransport mRestoreTransport = null;
2335 RestoreSet[] mRestoreSets = null;
2336
Christopher Tate80202c82010-01-25 19:37:47 -08002337 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002338 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002339 }
2340
2341 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002342 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002344 "getAvailableRestoreSets");
2345
Christopher Tate1bb69062010-02-19 17:02:12 -08002346 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002347 try {
Christopher Tate43383042009-07-13 15:17:13 -07002348 if (mRestoreTransport == null) {
2349 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002350 return null;
2351 }
2352 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002353 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002354 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002355 }
2356 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002357 } catch (Exception e) {
2358 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2359 return null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002360 } finally {
2361 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002362 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002363 }
2364
Christopher Tate84725812010-02-04 15:52:40 -08002365 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2367 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002368
Christopher Tatef2c321a2009-08-10 15:43:36 -07002369 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2370 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002371
Dan Egnor0084da52009-07-29 12:57:16 -07002372 if (mRestoreTransport == null || mRestoreSets == null) {
2373 Log.e(TAG, "Ignoring performRestore() with no restore set");
2374 return -1;
2375 }
2376
Christopher Tate21ab6a52009-09-24 18:01:46 -07002377 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002378 for (int i = 0; i < mRestoreSets.length; i++) {
2379 if (token == mRestoreSets[i].token) {
2380 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002381 mWakelock.acquire();
2382 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2383 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2384 mBackupHandler.sendMessage(msg);
2385 Binder.restoreCallingIdentity(oldId);
2386 return 0;
2387 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002388 }
2389 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002390
2391 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002392 return -1;
2393 }
2394
Christopher Tate84725812010-02-04 15:52:40 -08002395 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
2396 if (DEBUG) Log.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
2397
2398 PackageInfo app = null;
2399 try {
2400 app = mPackageManager.getPackageInfo(packageName, 0);
2401 } catch (NameNotFoundException nnf) {
2402 Log.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2403 return -1;
2404 }
2405
2406 // If the caller is not privileged and is not coming from the target
2407 // app's uid, throw a permission exception back to the caller.
2408 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2409 Binder.getCallingPid(), Binder.getCallingUid());
2410 if ((perm == PackageManager.PERMISSION_DENIED) &&
2411 (app.applicationInfo.uid != Binder.getCallingUid())) {
2412 Log.w(TAG, "restorePackage: bad packageName=" + packageName
2413 + " or calling uid=" + Binder.getCallingUid());
2414 throw new SecurityException("No permission to restore other packages");
2415 }
2416
2417 // So far so good; we're allowed to try to restore this package. Now
2418 // check whether there is data for it in the current dataset, falling back
2419 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002420 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002421
2422 // If we didn't come up with a place to look -- no ancestral dataset and
2423 // the app has never been backed up from this device -- there's nothing
2424 // to do but return failure.
2425 if (token == 0) {
2426 return -1;
2427 }
2428
2429 // Ready to go: enqueue the restore request and claim success
2430 long oldId = Binder.clearCallingIdentity();
2431 mWakelock.acquire();
2432 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002433 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002434 mBackupHandler.sendMessage(msg);
2435 Binder.restoreCallingIdentity(oldId);
2436 return 0;
2437 }
2438
Dan Egnor0084da52009-07-29 12:57:16 -07002439 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002440 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002441 "endRestoreSession");
2442
Dan Egnor0084da52009-07-29 12:57:16 -07002443 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002444
Dan Egnor0084da52009-07-29 12:57:16 -07002445 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002446 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002447 try {
2448 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2449 } catch (Exception e) {
2450 Log.e(TAG, "Error in finishRestore", e);
2451 } finally {
2452 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002453 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002454 }
2455 }
2456
2457 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002458 if (BackupManagerService.this.mActiveRestoreSession == this) {
2459 BackupManagerService.this.mActiveRestoreSession = null;
2460 } else {
2461 Log.e(TAG, "ending non-current restore session");
2462 }
2463 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002464 }
2465 }
2466
Christopher Tate043dadc2009-06-02 16:11:00 -07002467
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002468 @Override
2469 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2470 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002471 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002472 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002473 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tate55f931a2009-09-29 17:17:34 -07002474 pw.println("Last backup pass: " + mLastBackupPass
2475 + " (now = " + System.currentTimeMillis() + ')');
2476 pw.println(" next scheduled: " + mNextBackupPass);
2477
Christopher Tate91717492009-06-26 21:07:13 -07002478 pw.println("Available transports:");
2479 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002480 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2481 try {
2482 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2483 for (File f : dir.listFiles()) {
2484 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2485 }
2486 } catch (RemoteException e) {
2487 Log.e(TAG, "Error in transportDirName()", e);
2488 pw.println(" Error: " + e);
2489 }
Christopher Tate91717492009-06-26 21:07:13 -07002490 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002491
2492 pw.println("Pending init: " + mPendingInits.size());
2493 for (String s : mPendingInits) {
2494 pw.println(" " + s);
2495 }
2496
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002497 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002498 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002499 for (int i=0; i<N; i++) {
2500 int uid = mBackupParticipants.keyAt(i);
2501 pw.print(" uid: ");
2502 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002503 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2504 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002505 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002506 }
2507 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002508
Christopher Tateb49ceb32010-02-08 16:22:24 -08002509 pw.println("Ancestral packages: "
2510 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
2511 for (String pkg : mAncestralPackages) {
2512 pw.println(" " + pkg);
2513 }
2514
Christopher Tate73e02522009-07-15 14:18:26 -07002515 pw.println("Ever backed up: " + mEverStoredApps.size());
2516 for (String pkg : mEverStoredApps) {
2517 pw.println(" " + pkg);
2518 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002519
2520 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002521 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002522 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002523 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002524 }
2525 }
Christopher Tate487529a2009-04-29 14:03:25 -07002526}