blob: 6795bdd20b0db0ca624ba9dbc86fc97407abe7e0 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Oscar Montemayora8529f62009-11-18 10:14:20 -080025import android.backup.IBackupManager;
26import android.backup.IRestoreObserver;
27import android.backup.IRestoreSession;
28import android.backup.RestoreSet;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070031import android.content.Context;
32import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070033import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070034import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070035import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070036import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070037import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070038import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070039import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080040import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070041import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070044import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070045import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080046import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070050import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070051import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070052import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070054import android.os.SystemClock;
Oscar Montemayora8529f62009-11-18 10:14:20 -080055import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.util.Log;
58import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080059import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070060
Christopher Tated55e18a2009-09-21 10:12:59 -070061import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080063import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040073import java.util.ArrayList;
74import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070075import java.util.HashSet;
76import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070077import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070078import java.util.Random;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070082 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Dan Egnorc1c49c02009-10-30 17:35:39 -070088 // Random variation in backup scheduling time to avoid server load spikes
89 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
90
Christopher Tate8031a3d2009-07-06 16:36:05 -070091 // The amount of time between the initial provisioning of the device and
92 // the first backup pass.
93 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
94
Christopher Tate4cc86e12009-09-21 19:36:51 -070095 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
96 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
97 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070098 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070099 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700100 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700101 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700102 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate44a27902010-01-27 17:15:49 -0800103 private static final int MSG_TIMEOUT = 6;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700104
105 // Timeout interval for deciding that a bind or clear-data has taken too long
106 static final long TIMEOUT_INTERVAL = 10 * 1000;
107
Christopher Tate44a27902010-01-27 17:15:49 -0800108 // Timeout intervals for agent backup & restore operations
109 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
110 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
111
Christopher Tate487529a2009-04-29 14:03:25 -0700112 private Context mContext;
113 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700114 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700115 private PowerManager mPowerManager;
116 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800117 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700118
Christopher Tate73e02522009-07-15 14:18:26 -0700119 boolean mEnabled; // access to this is synchronized on 'this'
120 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800121 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700122 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800123 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
124 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700125 PendingIntent mRunBackupIntent, mRunInitIntent;
126 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700127 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700128 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700129 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700130 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700131 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700132 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700133 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700134
Christopher Tate181fafa2009-05-14 11:12:14 -0700135 BackupRequest(ApplicationInfo app, boolean isFull) {
136 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700137 fullBackup = isFull;
138 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700139
140 public String toString() {
141 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
142 }
Christopher Tate46758122009-05-06 11:22:00 -0700143 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400144 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700145 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700146 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700147
148 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700149 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700150
151 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700152 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700153
Christopher Tate043dadc2009-06-02 16:11:00 -0700154 // The thread performing the sequence of queued backups binds to each app's agent
155 // in succession. Bind notifications are asynchronously delivered through the
156 // Activity Manager; use this lock object to signal when a requested binding has
157 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700158 final Object mAgentConnectLock = new Object();
159 IBackupAgent mConnectedAgent;
160 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700161 volatile long mLastBackupPass;
162 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700163
Christopher Tate55f931a2009-09-29 17:17:34 -0700164 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700165 final Object mClearDataLock = new Object();
166 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700167
Christopher Tate91717492009-06-26 21:07:13 -0700168 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700169 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700170 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700171 String mCurrentTransport;
172 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800173 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700174
Christopher Tate73e02522009-07-15 14:18:26 -0700175 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700176 public IBackupTransport transport;
177 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700178 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800179 public PackageInfo pkgInfo;
180
181 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
182 long _token, PackageInfo _pkg) {
183 transport = _transport;
184 observer = _obs;
185 token = _token;
186 pkgInfo = _pkg;
187 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700188
Dan Egnor156411d2009-06-26 13:20:02 -0700189 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700190 transport = _transport;
191 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700192 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800193 pkgInfo = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700194 }
195 }
196
Christopher Tate73e02522009-07-15 14:18:26 -0700197 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700198 public IBackupTransport transport;
199 public PackageInfo packageInfo;
200
201 ClearParams(IBackupTransport _transport, PackageInfo _info) {
202 transport = _transport;
203 packageInfo = _info;
204 }
205 }
206
Christopher Tate44a27902010-01-27 17:15:49 -0800207 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
208 // token is the index of the entry in the pending-operations list.
209 static final int OP_PENDING = 0;
210 static final int OP_ACKNOWLEDGED = 1;
211 static final int OP_TIMEOUT = -1;
212
213 final SparseIntArray mCurrentOperations = new SparseIntArray();
214 final Object mCurrentOpLock = new Object();
215 final Random mTokenGenerator = new Random();
216
Christopher Tate5cb400b2009-06-25 16:03:14 -0700217 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700218 File mBaseStateDir;
219 File mDataDir;
220 File mJournalDir;
221 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700222
Christopher Tate84725812010-02-04 15:52:40 -0800223 // Keep a log of all the apps we've ever backed up, and what the
224 // dataset tokens are for both the current backup dataset and
225 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700226 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700227 HashSet<String> mEverStoredApps = new HashSet<String>();
228
Christopher Tate84725812010-02-04 15:52:40 -0800229 File mTokenFile;
230 long mAncestralToken = 0;
231 long mCurrentToken = 0;
232
Christopher Tate4cc86e12009-09-21 19:36:51 -0700233 // Persistently track the need to do a full init
234 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
235 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700236
Christopher Tate44a27902010-01-27 17:15:49 -0800237 // ----- Asynchronous backup/restore handler thread -----
238
239 private class BackupHandler extends Handler {
240 public BackupHandler(Looper looper) {
241 super(looper);
242 }
243
244 public void handleMessage(Message msg) {
245
246 switch (msg.what) {
247 case MSG_RUN_BACKUP:
248 {
249 mLastBackupPass = System.currentTimeMillis();
250 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
251
252 IBackupTransport transport = getTransport(mCurrentTransport);
253 if (transport == null) {
254 Log.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800255 mWakelock.release();
256 break;
257 }
258
259 // snapshot the pending-backup set and work on that
260 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
261 synchronized (mQueueLock) {
262 // Do we have any work to do?
263 if (mPendingBackups.size() > 0) {
264 for (BackupRequest b: mPendingBackups.values()) {
265 queue.add(b);
266 }
267 if (DEBUG) Log.v(TAG, "clearing pending backups");
268 mPendingBackups.clear();
269
270 // Start a new backup-queue journal file too
271 File oldJournal = mJournal;
272 mJournal = null;
273
274 // At this point, we have started a new journal file, and the old
275 // file identity is being passed to the backup processing thread.
276 // When it completes successfully, that old journal file will be
277 // deleted. If we crash prior to that, the old journal is parsed
278 // at next boot and the journaled requests fulfilled.
279 (new PerformBackupTask(transport, queue, oldJournal)).run();
280 } else {
281 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tate44a27902010-01-27 17:15:49 -0800282 mWakelock.release();
283 }
284 }
285 break;
286 }
287
288 case MSG_RUN_FULL_BACKUP:
289 break;
290
291 case MSG_RUN_RESTORE:
292 {
293 RestoreParams params = (RestoreParams)msg.obj;
294 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
295 (new PerformRestoreTask(params.transport, params.observer,
Christopher Tate84725812010-02-04 15:52:40 -0800296 params.token, params.pkgInfo)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800297 break;
298 }
299
300 case MSG_RUN_CLEAR:
301 {
302 ClearParams params = (ClearParams)msg.obj;
303 (new PerformClearTask(params.transport, params.packageInfo)).run();
304 break;
305 }
306
307 case MSG_RUN_INITIALIZE:
308 {
309 HashSet<String> queue;
310
311 // Snapshot the pending-init queue and work on that
312 synchronized (mQueueLock) {
313 queue = new HashSet<String>(mPendingInits);
314 mPendingInits.clear();
315 }
316
317 (new PerformInitializeTask(queue)).run();
318 break;
319 }
320
321 case MSG_TIMEOUT:
322 {
323 synchronized (mCurrentOpLock) {
324 final int token = msg.arg1;
325 int state = mCurrentOperations.get(token, OP_TIMEOUT);
326 if (state == OP_PENDING) {
327 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
328 mCurrentOperations.put(token, OP_TIMEOUT);
329 }
330 mCurrentOpLock.notifyAll();
331 }
332 break;
333 }
334 }
335 }
336 }
337
338 // ----- Main service implementation -----
339
Christopher Tate487529a2009-04-29 14:03:25 -0700340 public BackupManagerService(Context context) {
341 mContext = context;
342 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700343 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700344
Christopher Tateb6787f22009-07-02 17:40:45 -0700345 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
346 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
347
Christopher Tate44a27902010-01-27 17:15:49 -0800348 mBackupManagerBinder = asInterface(asBinder());
349
350 // spin up the backup/restore handler thread
351 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
352 mHandlerThread.start();
353 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
354
Christopher Tate22b87872009-05-04 16:41:53 -0700355 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700356 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700357 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700358 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700359 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800360 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
361 Settings.Secure.BACKUP_AUTO_RESTORE, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800362 // If Encrypted file systems is enabled or disabled, this call will return the
363 // correct directory.
364 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
365 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700366 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700367
Christopher Tate4cc86e12009-09-21 19:36:51 -0700368 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700369 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700370 IntentFilter filter = new IntentFilter();
371 filter.addAction(RUN_BACKUP_ACTION);
372 context.registerReceiver(mRunBackupReceiver, filter,
373 android.Manifest.permission.BACKUP, null);
374
375 mRunInitReceiver = new RunInitializeReceiver();
376 filter = new IntentFilter();
377 filter.addAction(RUN_INITIALIZE_ACTION);
378 context.registerReceiver(mRunInitReceiver, filter,
379 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700380
381 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700382 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
383 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
384
Christopher Tate4cc86e12009-09-21 19:36:51 -0700385 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
386 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
387 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
388
Christopher Tatecde87f42009-06-12 12:55:53 -0700389 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700390 mJournalDir = new File(mBaseStateDir, "pending");
391 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700392 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700393
Christopher Tate73e02522009-07-15 14:18:26 -0700394 // Set up the various sorts of package tracking we do
395 initPackageTracking();
396
Christopher Tateabce4e82009-06-18 18:35:32 -0700397 // Build our mapping of uid to backup client services. This implicitly
398 // schedules a backup pass on the Package Manager metadata the first
399 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700400 synchronized (mBackupParticipants) {
401 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700402 }
403
Dan Egnor87a02bc2009-06-17 02:30:10 -0700404 // Set up our transport options and initialize the default transport
405 // TODO: Have transports register themselves somehow?
406 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700407 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700408 ComponentName localName = new ComponentName(context, LocalTransport.class);
409 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700410
Christopher Tate91717492009-06-26 21:07:13 -0700411 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700412 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
413 Settings.Secure.BACKUP_TRANSPORT);
414 if ("".equals(mCurrentTransport)) {
415 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700416 }
Christopher Tate91717492009-06-26 21:07:13 -0700417 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
418
419 // Attach to the Google backup transport. When this comes up, it will set
420 // itself as the current transport because we explicitly reset mCurrentTransport
421 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700422 Intent intent = new Intent().setComponent(new ComponentName(
423 "com.google.android.backup",
424 "com.google.android.backup.BackupTransportService"));
425 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700426
Christopher Tatecde87f42009-06-12 12:55:53 -0700427 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700428 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700429 parseLeftoverJournals();
430
Christopher Tateb6787f22009-07-02 17:40:45 -0700431 // Power management
432 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
433
434 // Start the backup passes going
435 setBackupEnabled(areEnabled);
436 }
437
438 private class RunBackupReceiver extends BroadcastReceiver {
439 public void onReceive(Context context, Intent intent) {
440 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700441 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700442 if (mPendingInits.size() > 0) {
443 // If there are pending init operations, we process those
444 // and then settle into the usual periodic backup schedule.
445 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
446 try {
447 mAlarmManager.cancel(mRunInitIntent);
448 mRunInitIntent.send();
449 } catch (PendingIntent.CanceledException ce) {
450 Log.e(TAG, "Run init intent cancelled");
451 // can't really do more than bail here
452 }
453 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800454 // Don't run backups now if we're disabled or not yet
455 // fully set up.
456 if (mEnabled && mProvisioned) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700457 if (DEBUG) Log.v(TAG, "Running a backup pass");
458
459 // Acquire the wakelock and pass it to the backup thread. it will
460 // be released once backup concludes.
461 mWakelock.acquire();
462
463 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
464 mBackupHandler.sendMessage(msg);
465 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800466 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700467 }
468 }
469 }
470 }
471 }
472 }
473
474 private class RunInitializeReceiver extends BroadcastReceiver {
475 public void onReceive(Context context, Intent intent) {
476 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
477 synchronized (mQueueLock) {
478 if (DEBUG) Log.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700479
480 // Acquire the wakelock and pass it to the init thread. it will
481 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700482 mWakelock.acquire();
483
Christopher Tate4cc86e12009-09-21 19:36:51 -0700484 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700485 mBackupHandler.sendMessage(msg);
486 }
487 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700488 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700489 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700490
Christopher Tate73e02522009-07-15 14:18:26 -0700491 private void initPackageTracking() {
492 if (DEBUG) Log.v(TAG, "Initializing package tracking");
493
Christopher Tate84725812010-02-04 15:52:40 -0800494 // Remember our ancestral dataset
495 mTokenFile = new File(mBaseStateDir, "ancestral");
496 try {
497 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
498 mAncestralToken = tf.readLong();
499 mCurrentToken = tf.readLong();
500 } catch (IOException e) {
501 Log.w(TAG, "Unable to read token file", e);
502 }
503
Christopher Tatee97e8072009-07-15 16:45:50 -0700504 // Keep a log of what apps we've ever backed up. Because we might have
505 // rebooted in the middle of an operation that was removing something from
506 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700507 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700508 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700509
Christopher Tatee97e8072009-07-15 16:45:50 -0700510 // If we were in the middle of removing something from the ever-backed-up
511 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700512 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700513 if (tempProcessedFile.exists()) {
514 tempProcessedFile.delete();
515 }
516
Dan Egnor852f8e42009-09-30 11:20:45 -0700517 // If there are previous contents, parse them out then start a new
518 // file to continue the recordkeeping.
519 if (mEverStored.exists()) {
520 RandomAccessFile temp = null;
521 RandomAccessFile in = null;
522
523 try {
524 temp = new RandomAccessFile(tempProcessedFile, "rws");
525 in = new RandomAccessFile(mEverStored, "r");
526
527 while (true) {
528 PackageInfo info;
529 String pkg = in.readUTF();
530 try {
531 info = mPackageManager.getPackageInfo(pkg, 0);
532 mEverStoredApps.add(pkg);
533 temp.writeUTF(pkg);
534 if (DEBUG) Log.v(TAG, " + " + pkg);
535 } catch (NameNotFoundException e) {
536 // nope, this package was uninstalled; don't include it
537 if (DEBUG) Log.v(TAG, " - " + pkg);
538 }
539 }
540 } catch (EOFException e) {
541 // Once we've rewritten the backup history log, atomically replace the
542 // old one with the new one then reopen the file for continuing use.
543 if (!tempProcessedFile.renameTo(mEverStored)) {
544 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
545 }
546 } catch (IOException e) {
547 Log.e(TAG, "Error in processed file", e);
548 } finally {
549 try { if (temp != null) temp.close(); } catch (IOException e) {}
550 try { if (in != null) in.close(); } catch (IOException e) {}
551 }
552 }
553
Christopher Tate73e02522009-07-15 14:18:26 -0700554 // Register for broadcasts about package install, etc., so we can
555 // update the provider list.
556 IntentFilter filter = new IntentFilter();
557 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
558 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
559 filter.addDataScheme("package");
560 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800561 // Register for events related to sdcard installation.
562 IntentFilter sdFilter = new IntentFilter();
563 sdFilter.addAction(Intent.ACTION_MEDIA_RESOURCES_AVAILABLE);
564 sdFilter.addAction(Intent.ACTION_MEDIA_RESOURCES_UNAVAILABLE);
565 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700566 }
567
Christopher Tatecde87f42009-06-12 12:55:53 -0700568 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700569 for (File f : mJournalDir.listFiles()) {
570 if (mJournal == null || f.compareTo(mJournal) != 0) {
571 // This isn't the current journal, so it must be a leftover. Read
572 // out the package names mentioned there and schedule them for
573 // backup.
574 RandomAccessFile in = null;
575 try {
576 Log.i(TAG, "Found stale backup journal, scheduling:");
577 in = new RandomAccessFile(f, "r");
578 while (true) {
579 String packageName = in.readUTF();
580 Log.i(TAG, " + " + packageName);
581 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700582 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700583 } catch (EOFException e) {
584 // no more data; we're done
585 } catch (Exception e) {
586 Log.e(TAG, "Can't read " + f, e);
587 } finally {
588 // close/delete the file
589 try { if (in != null) in.close(); } catch (IOException e) {}
590 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700591 }
592 }
593 }
594 }
595
Christopher Tate4cc86e12009-09-21 19:36:51 -0700596 // Maintain persistent state around whether need to do an initialize operation.
597 // Must be called with the queue lock held.
598 void recordInitPendingLocked(boolean isPending, String transportName) {
599 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
600 + " on transport " + transportName);
601 try {
602 IBackupTransport transport = getTransport(transportName);
603 String transportDirName = transport.transportDirName();
604 File stateDir = new File(mBaseStateDir, transportDirName);
605 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
606
607 if (isPending) {
608 // We need an init before we can proceed with sending backup data.
609 // Record that with an entry in our set of pending inits, as well as
610 // journaling it via creation of a sentinel file.
611 mPendingInits.add(transportName);
612 try {
613 (new FileOutputStream(initPendingFile)).close();
614 } catch (IOException ioe) {
615 // Something is badly wrong with our permissions; just try to move on
616 }
617 } else {
618 // No more initialization needed; wipe the journal and reset our state.
619 initPendingFile.delete();
620 mPendingInits.remove(transportName);
621 }
622 } catch (RemoteException e) {
623 // can't happen; the transport is local
624 }
625 }
626
Christopher Tated55e18a2009-09-21 10:12:59 -0700627 // Reset all of our bookkeeping, in response to having been told that
628 // the backend data has been wiped [due to idle expiry, for example],
629 // so we must re-upload all saved settings.
630 void resetBackupState(File stateFileDir) {
631 synchronized (mQueueLock) {
632 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700633 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700634 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700635
Christopher Tate84725812010-02-04 15:52:40 -0800636 mCurrentToken = 0;
637 writeRestoreTokens();
638
Christopher Tated55e18a2009-09-21 10:12:59 -0700639 // Remove all the state files
640 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700641 // ... but don't touch the needs-init sentinel
642 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
643 sf.delete();
644 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700645 }
646
647 // Enqueue a new backup of every participant
648 int N = mBackupParticipants.size();
649 for (int i=0; i<N; i++) {
650 int uid = mBackupParticipants.keyAt(i);
651 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
652 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700653 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700654 }
655 }
656 }
657 }
658
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800659 // Add a transport to our set of available backends. If 'transport' is null, this
660 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700661 private void registerTransport(String name, IBackupTransport transport) {
662 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700663 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800664 if (transport != null) {
665 mTransports.put(name, transport);
666 } else {
667 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800668 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800669 mCurrentTransport = null;
670 }
671 // Nothing further to do in the unregistration case
672 return;
673 }
Christopher Tate91717492009-06-26 21:07:13 -0700674 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675
676 // If the init sentinel file exists, we need to be sure to perform the init
677 // as soon as practical. We also create the state directory at registration
678 // time to ensure it's present from the outset.
679 try {
680 String transportName = transport.transportDirName();
681 File stateDir = new File(mBaseStateDir, transportName);
682 stateDir.mkdirs();
683
684 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
685 if (initSentinel.exists()) {
686 synchronized (mQueueLock) {
687 mPendingInits.add(transportName);
688
689 // TODO: pick a better starting time than now + 1 minute
690 long delay = 1000 * 60; // one minute, in milliseconds
691 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
692 System.currentTimeMillis() + delay, mRunInitIntent);
693 }
694 }
695 } catch (RemoteException e) {
696 // can't happen, the transport is local
697 }
Christopher Tate91717492009-06-26 21:07:13 -0700698 }
699
Christopher Tate3799bc22009-05-06 16:13:56 -0700700 // ----- Track installation/removal of packages -----
701 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
702 public void onReceive(Context context, Intent intent) {
703 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
704
Christopher Tate3799bc22009-05-06 16:13:56 -0700705 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800706 boolean replacing = false;
707 boolean added = false;
708 Bundle extras = intent.getExtras();
709 String pkgList[] = null;
710 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
711 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
712 Uri uri = intent.getData();
713 if (uri == null) {
714 return;
715 }
716 String pkgName = uri.getSchemeSpecificPart();
717 if (pkgName != null) {
718 pkgList = new String[] { pkgName };
719 }
720 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
721 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
722 } else if (Intent.ACTION_MEDIA_RESOURCES_AVAILABLE.equals(action)) {
723 added = true;
724 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
725 } else if (Intent.ACTION_MEDIA_RESOURCES_UNAVAILABLE.equals(action)) {
726 added = false;
727 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
728 }
729 if (pkgList == null || pkgList.length == 0) {
730 return;
731 }
732 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700733 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800734 for (String pkgName : pkgList) {
735 if (replacing) {
736 // The package was just upgraded
737 updatePackageParticipantsLocked(pkgName);
738 } else {
739 // The package was just added
740 addPackageParticipantsLocked(pkgName);
741 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700742 }
743 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800744 } else {
745 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700746 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
747 } else {
748 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800749 for (String pkgName : pkgList) {
750 removePackageParticipantsLocked(pkgName);
751 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700752 }
753 }
754 }
755 }
756 };
757
Dan Egnor87a02bc2009-06-17 02:30:10 -0700758 // ----- Track connection to GoogleBackupTransport service -----
759 ServiceConnection mGoogleConnection = new ServiceConnection() {
760 public void onServiceConnected(ComponentName name, IBinder service) {
761 if (DEBUG) Log.v(TAG, "Connected to Google transport");
762 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700763 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700764 }
765
766 public void onServiceDisconnected(ComponentName name) {
767 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
768 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700769 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700770 }
771 };
772
Christopher Tate181fafa2009-05-14 11:12:14 -0700773 // Add the backup agents in the given package to our set of known backup participants.
774 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700775 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700776 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700777 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700778 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700779 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700780 }
781
Christopher Tate181fafa2009-05-14 11:12:14 -0700782 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700783 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700784 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700785 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
786 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700787 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700788 + " uid=" + p.applicationInfo.uid
789 + " killAfterRestore="
790 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
791 + " restoreNeedsApplication="
792 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
793 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700794 }
795 }
796
Dan Egnorefe52642009-06-24 00:16:33 -0700797 for (PackageInfo pkg : targetPkgs) {
798 if (packageName == null || pkg.packageName.equals(packageName)) {
799 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700800 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700801 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700802 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700803 mBackupParticipants.put(uid, set);
804 }
Dan Egnorefe52642009-06-24 00:16:33 -0700805 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700806
807 // If we've never seen this app before, schedule a backup for it
808 if (!mEverStoredApps.contains(pkg.packageName)) {
809 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
810 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700811 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700812 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700813 }
Christopher Tate487529a2009-04-29 14:03:25 -0700814 }
815 }
816
Christopher Tate6785dd82009-06-18 15:58:25 -0700817 // Remove the given package's entry from our known active set. If
818 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700819 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700820 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700821 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700822 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700823 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700824 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700825 int flags = PackageManager.GET_SIGNATURES;
826 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700827 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700828 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700829 }
830 } else {
831 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700832 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700833 }
834 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700835 }
836
Joe Onorato8ad02812009-05-13 01:41:44 -0400837 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700838 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700839 if (DEBUG) {
840 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
841 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700842 for (PackageInfo p : agents) {
843 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700844 }
845 }
Dan Egnorefe52642009-06-24 00:16:33 -0700846 for (PackageInfo pkg : agents) {
847 if (packageName == null || pkg.packageName.equals(packageName)) {
848 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700849 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700850 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700851 // Find the existing entry with the same package name, and remove it.
852 // We can't just remove(app) because the instances are different.
853 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700854 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700855 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700856 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700857 break;
858 }
859 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700860 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700861 mBackupParticipants.delete(uid);
862 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700863 }
864 }
865 }
866 }
867
Christopher Tate181fafa2009-05-14 11:12:14 -0700868 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700869 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700870 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700871 int flags = PackageManager.GET_SIGNATURES;
872 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
873 int N = packages.size();
874 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700875 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700876 try {
877 ApplicationInfo app = pkg.applicationInfo;
878 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
879 || app.backupAgentName == null
880 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
881 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
882 packages.remove(a);
883 }
884 else {
885 // we will need the shared library path, so look that up and store it here
886 app = mPackageManager.getApplicationInfo(pkg.packageName,
887 PackageManager.GET_SHARED_LIBRARY_FILES);
888 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
889 }
890 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700891 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700892 }
893 }
Dan Egnorefe52642009-06-24 00:16:33 -0700894 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700895 }
Christopher Tateaa088442009-06-16 18:25:46 -0700896
Christopher Tate3799bc22009-05-06 16:13:56 -0700897 // Reset the given package's known backup participants. Unlike add/remove, the update
898 // action cannot be passed a null package name.
899 void updatePackageParticipantsLocked(String packageName) {
900 if (packageName == null) {
901 Log.e(TAG, "updatePackageParticipants called with null package name");
902 return;
903 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700904 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700905
906 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700907 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700908 removePackageParticipantsLockedInner(packageName, allApps);
909 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700910 }
911
Christopher Tate84725812010-02-04 15:52:40 -0800912 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -0700913 // backed up at least once
914 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700915 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
916
917 synchronized (mEverStoredApps) {
918 if (!mEverStoredApps.add(packageName)) return;
919
920 RandomAccessFile out = null;
921 try {
922 out = new RandomAccessFile(mEverStored, "rws");
923 out.seek(out.length());
924 out.writeUTF(packageName);
925 } catch (IOException e) {
926 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
927 } finally {
928 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700929 }
930 }
931 }
932
Christopher Tatee97e8072009-07-15 16:45:50 -0700933 // Remove our awareness of having ever backed up the given package
934 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700935 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700936
Dan Egnor852f8e42009-09-30 11:20:45 -0700937 synchronized (mEverStoredApps) {
938 // Rewrite the file and rename to overwrite. If we reboot in the middle,
939 // we'll recognize on initialization time that the package no longer
940 // exists and fix it up then.
941 File tempKnownFile = new File(mBaseStateDir, "processed.new");
942 RandomAccessFile known = null;
943 try {
944 known = new RandomAccessFile(tempKnownFile, "rws");
945 mEverStoredApps.remove(packageName);
946 for (String s : mEverStoredApps) {
947 known.writeUTF(s);
948 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700949 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700950 known.close();
951 known = null;
952 if (!tempKnownFile.renameTo(mEverStored)) {
953 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
954 }
955 } catch (IOException e) {
956 // Bad: we couldn't create the new copy. For safety's sake we
957 // abandon the whole process and remove all what's-backed-up
958 // state entirely, meaning we'll force a backup pass for every
959 // participant on the next boot or [re]install.
960 Log.w(TAG, "Error rewriting " + mEverStored, e);
961 mEverStoredApps.clear();
962 tempKnownFile.delete();
963 mEverStored.delete();
964 } finally {
965 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700966 }
967 }
968 }
969
Christopher Tate84725812010-02-04 15:52:40 -0800970 // Record the current and ancestral backup tokens persistently
971 void writeRestoreTokens() {
972 try {
973 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
974 af.writeLong(mAncestralToken);
975 af.writeLong(mCurrentToken);
976 af.close();
977 } catch (IOException e) {
978 Log.w(TAG, "Unable to write token file:", e);
979 }
980 }
981
Dan Egnor87a02bc2009-06-17 02:30:10 -0700982 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700983 private IBackupTransport getTransport(String transportName) {
984 synchronized (mTransports) {
985 IBackupTransport transport = mTransports.get(transportName);
986 if (transport == null) {
987 Log.w(TAG, "Requested unavailable transport: " + transportName);
988 }
989 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700990 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700991 }
992
Christopher Tatedf01dea2009-06-09 20:45:02 -0700993 // fire off a backup agent, blocking until it attaches or times out
994 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
995 IBackupAgent agent = null;
996 synchronized(mAgentConnectLock) {
997 mConnecting = true;
998 mConnectedAgent = null;
999 try {
1000 if (mActivityManager.bindBackupAgent(app, mode)) {
1001 Log.d(TAG, "awaiting agent for " + app);
1002
1003 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001004 // only wait 10 seconds for the clear data to happen
1005 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1006 while (mConnecting && mConnectedAgent == null
1007 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001008 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001009 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001010 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001011 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001012 return null;
1013 }
1014 }
1015
1016 // if we timed out with no connect, abort and move on
1017 if (mConnecting == true) {
1018 Log.w(TAG, "Timeout waiting for agent " + app);
1019 return null;
1020 }
1021 agent = mConnectedAgent;
1022 }
1023 } catch (RemoteException e) {
1024 // can't happen
1025 }
1026 }
1027 return agent;
1028 }
1029
Christopher Tatec7b31e32009-06-10 15:49:30 -07001030 // clear an application's data, blocking until the operation completes or times out
1031 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001032 // Don't wipe packages marked allowClearUserData=false
1033 try {
1034 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1035 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1036 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
1037 + packageName);
1038 return;
1039 }
1040 } catch (NameNotFoundException e) {
1041 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
1042 return;
1043 }
1044
Christopher Tatec7b31e32009-06-10 15:49:30 -07001045 ClearDataObserver observer = new ClearDataObserver();
1046
1047 synchronized(mClearDataLock) {
1048 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001049 /* This is causing some critical processes to be killed during setup.
1050 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -07001051 try {
1052 mActivityManager.clearApplicationUserData(packageName, observer);
1053 } catch (RemoteException e) {
1054 // can't happen because the activity manager is in this process
1055 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001056 */
1057 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001058
1059 // only wait 10 seconds for the clear data to happen
1060 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1061 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1062 try {
1063 mClearDataLock.wait(5000);
1064 } catch (InterruptedException e) {
1065 // won't happen, but still.
1066 mClearingData = false;
1067 }
1068 }
1069 }
1070 }
1071
1072 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001073 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001074 synchronized(mClearDataLock) {
1075 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001076 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001077 }
1078 }
1079 }
1080
Christopher Tate44a27902010-01-27 17:15:49 -08001081 // -----
1082 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1083 boolean waitUntilOperationComplete(int token) {
1084 int finalState = OP_PENDING;
1085 synchronized (mCurrentOpLock) {
1086 try {
1087 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1088 try {
1089 mCurrentOpLock.wait();
1090 } catch (InterruptedException e) {}
1091 }
1092 } catch (IndexOutOfBoundsException e) {
1093 // the operation has been mysteriously cleared from our
1094 // bookkeeping -- consider this a success and ignore it.
1095 }
1096 }
1097 mBackupHandler.removeMessages(MSG_TIMEOUT);
1098 if (DEBUG) Log.v(TAG, "operation " + token + " complete: finalState=" + finalState);
1099 return finalState == OP_ACKNOWLEDGED;
1100 }
1101
1102 void prepareOperationTimeout(int token, long interval) {
1103 if (DEBUG) Log.v(TAG, "starting timeout: token=" + token + " interval=" + interval);
1104 mCurrentOperations.put(token, OP_PENDING);
1105 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1106 mBackupHandler.sendMessageDelayed(msg, interval);
1107 }
1108
Christopher Tate043dadc2009-06-02 16:11:00 -07001109 // ----- Back up a set of applications via a worker thread -----
1110
Christopher Tate44a27902010-01-27 17:15:49 -08001111 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001112 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001113 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001114 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001115 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001116 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001117
Christopher Tate44a27902010-01-27 17:15:49 -08001118 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001119 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001120 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001121 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001122 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001123
1124 try {
1125 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1126 } catch (RemoteException e) {
1127 // can't happen; the transport is local
1128 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001129 }
1130
Christopher Tate043dadc2009-06-02 16:11:00 -07001131 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001132 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001133 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001134 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1135
Christopher Tate79588342009-06-30 16:11:49 -07001136 // Backups run at background priority
1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138
Christopher Tate043dadc2009-06-02 16:11:00 -07001139 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001140 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001141
Dan Egnor852f8e42009-09-30 11:20:45 -07001142 // If we haven't stored package manager metadata yet, we must init the transport.
1143 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1144 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1145 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1146 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001147 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001148 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001149 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001150 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001151 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001152 Log.e(TAG, "Transport error in initializeDevice()");
1153 }
Dan Egnor01445162009-09-21 17:04:05 -07001154 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001155
1156 // The package manager doesn't have a proper <application> etc, but since
1157 // it's running here in the system process we can just set up its agent
1158 // directly and use a synthetic BackupRequest. We always run this pass
1159 // because it's cheap and this way we guarantee that we don't get out of
1160 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001161 if (status == BackupConstants.TRANSPORT_OK) {
1162 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1163 mPackageManager, allAgentPackages());
1164 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1165 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1166 status = processOneBackup(pmRequest,
1167 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1168 }
Christopher Tate90967f42009-09-20 15:28:33 -07001169
Dan Egnor01445162009-09-21 17:04:05 -07001170 if (status == BackupConstants.TRANSPORT_OK) {
1171 // Now run all the backups in our queue
1172 status = doQueuedBackups(mTransport);
1173 }
1174
1175 if (status == BackupConstants.TRANSPORT_OK) {
1176 // Tell the transport to finish everything it has buffered
1177 status = mTransport.finishBackup();
1178 if (status == BackupConstants.TRANSPORT_OK) {
1179 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001180 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001181 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001182 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001183 Log.e(TAG, "Transport error in finishBackup()");
1184 }
1185 }
1186
Dan Egnor01445162009-09-21 17:04:05 -07001187 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001188 // The backend reports that our dataset has been wiped. We need to
1189 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001190 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001192 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001193 }
1194 } catch (Exception e) {
1195 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001196 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001197 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001198 // If everything actually went through and this is the first time we've
1199 // done a backup, we can now record what the current backup dataset token
1200 // is.
1201 if ((mCurrentToken == 0) && (status != BackupConstants.TRANSPORT_OK)) {
1202 try {
1203 mCurrentToken = mTransport.getCurrentRestoreSet();
1204 } catch (RemoteException e) { /* cannot happen */ }
1205 writeRestoreTokens();
1206 }
1207
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001208 // If things went wrong, we need to re-stage the apps we had expected
1209 // to be backing up in this pass. This journals the package names in
1210 // the current active pending-backup file, not in the we are holding
1211 // here in mJournal.
1212 if (status != BackupConstants.TRANSPORT_OK) {
1213 Log.w(TAG, "Backup pass unsuccessful, restaging");
1214 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001215 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001216 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001217
1218 // We also want to reset the backup schedule based on whatever
1219 // the transport suggests by way of retry/backoff time.
1220 try {
1221 startBackupAlarmsLocked(mTransport.requestBackupTime());
1222 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001223 }
1224
1225 // Either backup was successful, in which case we of course do not need
1226 // this pass's journal any more; or it failed, in which case we just
1227 // re-enqueued all of these packages in the current active journal.
1228 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001229 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001230 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1231 }
1232
Christopher Tatec2af5d32010-02-02 15:18:58 -08001233 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001234 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001235 backupNow();
1236 }
1237
Dan Egnorbb9001c2009-07-27 12:20:13 -07001238 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001239 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001240 }
1241
Dan Egnor01445162009-09-21 17:04:05 -07001242 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001243 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001244 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001245
Christopher Tate0749dcd2009-08-13 15:13:03 -07001246 // Don't run backup, even if requested, if the target app does not have
1247 // the requisite permission
1248 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1249 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1250 Log.w(TAG, "Skipping backup of unprivileged package "
1251 + request.appInfo.packageName);
1252 continue;
1253 }
1254
Christopher Tate043dadc2009-06-02 16:11:00 -07001255 IBackupAgent agent = null;
1256 int mode = (request.fullBackup)
1257 ? IApplicationThread.BACKUP_MODE_FULL
1258 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1259 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001260 agent = bindToAgentSynchronous(request.appInfo, mode);
1261 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001262 int result = processOneBackup(request, agent, transport);
1263 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001264 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001265 } catch (SecurityException ex) {
1266 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001267 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001268 } finally {
1269 try { // unbind even on timeout, just in case
1270 mActivityManager.unbindBackupAgent(request.appInfo);
1271 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001272 }
1273 }
Dan Egnor01445162009-09-21 17:04:05 -07001274
1275 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001276 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001277
Dan Egnor01445162009-09-21 17:04:05 -07001278 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1279 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001280 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001281 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001282
Dan Egnorbb9001c2009-07-27 12:20:13 -07001283 File savedStateName = new File(mStateDir, packageName);
1284 File backupDataName = new File(mDataDir, packageName + ".data");
1285 File newStateName = new File(mStateDir, packageName + ".new");
1286
1287 ParcelFileDescriptor savedState = null;
1288 ParcelFileDescriptor backupData = null;
1289 ParcelFileDescriptor newState = null;
1290
1291 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001292 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001293 try {
1294 // Look up the package info & signatures. This is first so that if it
1295 // throws an exception, there's no file setup yet that would need to
1296 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001297 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1298 // The metadata 'package' is synthetic
1299 packInfo = new PackageInfo();
1300 packInfo.packageName = packageName;
1301 } else {
1302 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001303 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001304 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001305
Christopher Tatec7b31e32009-06-10 15:49:30 -07001306 // In a full backup, we pass a null ParcelFileDescriptor as
1307 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308 if (!request.fullBackup) {
1309 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001310 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001311 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1312 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001313
Dan Egnorbb9001c2009-07-27 12:20:13 -07001314 backupData = ParcelFileDescriptor.open(backupDataName,
1315 ParcelFileDescriptor.MODE_READ_WRITE |
1316 ParcelFileDescriptor.MODE_CREATE |
1317 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001318
Dan Egnorbb9001c2009-07-27 12:20:13 -07001319 newState = ParcelFileDescriptor.open(newStateName,
1320 ParcelFileDescriptor.MODE_READ_WRITE |
1321 ParcelFileDescriptor.MODE_CREATE |
1322 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001323
Christopher Tate44a27902010-01-27 17:15:49 -08001324 // Initiate the target's backup pass
1325 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1326 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1327 boolean success = waitUntilOperationComplete(token);
1328
1329 if (!success) {
1330 // timeout -- bail out into the failed-transaction logic
1331 throw new RuntimeException("Backup timeout");
1332 }
1333
Dan Egnorbb9001c2009-07-27 12:20:13 -07001334 logBackupComplete(packageName);
1335 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001336 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001337 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001338 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001339 backupDataName.delete();
1340 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001341 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001342 } finally {
1343 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1344 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1345 try { if (newState != null) newState.close(); } catch (IOException e) {}
1346 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001347 synchronized (mCurrentOpLock) {
1348 mCurrentOperations.clear();
1349 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001350 }
1351
1352 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001353 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001354 try {
1355 int size = (int) backupDataName.length();
1356 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001357 if (result == BackupConstants.TRANSPORT_OK) {
1358 backupData = ParcelFileDescriptor.open(backupDataName,
1359 ParcelFileDescriptor.MODE_READ_ONLY);
1360 result = transport.performBackup(packInfo, backupData);
1361 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001362
Dan Egnor83861e72009-09-17 16:17:55 -07001363 // TODO - We call finishBackup() for each application backed up, because
1364 // we need to know now whether it succeeded or failed. Instead, we should
1365 // hold off on finishBackup() until the end, which implies holding off on
1366 // renaming *all* the output state files (see below) until that happens.
1367
Dan Egnor01445162009-09-21 17:04:05 -07001368 if (result == BackupConstants.TRANSPORT_OK) {
1369 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001370 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001371 } else {
1372 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1373 }
1374
1375 // After successful transport, delete the now-stale data
1376 // and juggle the files so that next time we supply the agent
1377 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001378 if (result == BackupConstants.TRANSPORT_OK) {
1379 backupDataName.delete();
1380 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001381 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001382 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001383 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001384 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001385 } catch (Exception e) {
1386 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001387 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001388 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001389 } finally {
1390 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001391 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001392
Dan Egnor01445162009-09-21 17:04:05 -07001393 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001394 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001395 }
1396
Christopher Tatedf01dea2009-06-09 20:45:02 -07001397
1398 // ----- Restore handling -----
1399
Christopher Tate78dd4a72009-11-04 11:49:08 -08001400 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1401 // If the target resides on the system partition, we allow it to restore
1402 // data from the like-named package in a restore set even if the signatures
1403 // do not match. (Unlike general applications, those flashed to the system
1404 // partition will be signed with the device's platform certificate, so on
1405 // different phones the same system app will have different signatures.)
1406 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1407 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1408 return true;
1409 }
1410
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001411 // Allow unsigned apps, but not signed on one device and unsigned on the other
1412 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001413 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001414 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1415 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001416 if ((storedSigs == null || storedSigs.length == 0)
1417 && (deviceSigs == null || deviceSigs.length == 0)) {
1418 return true;
1419 }
1420 if (storedSigs == null || deviceSigs == null) {
1421 return false;
1422 }
1423
Christopher Tateabce4e82009-06-18 18:35:32 -07001424 // !!! TODO: this demands that every stored signature match one
1425 // that is present on device, and does not demand the converse.
1426 // Is this this right policy?
1427 int nStored = storedSigs.length;
1428 int nDevice = deviceSigs.length;
1429
1430 for (int i=0; i < nStored; i++) {
1431 boolean match = false;
1432 for (int j=0; j < nDevice; j++) {
1433 if (storedSigs[i].equals(deviceSigs[j])) {
1434 match = true;
1435 break;
1436 }
1437 }
1438 if (!match) {
1439 return false;
1440 }
1441 }
1442 return true;
1443 }
1444
Christopher Tate44a27902010-01-27 17:15:49 -08001445 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001446 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001447 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001448 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001449 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001450 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001451
Christopher Tate5cbbf562009-06-22 16:44:51 -07001452 class RestoreRequest {
1453 public PackageInfo app;
1454 public int storedAppVersion;
1455
1456 RestoreRequest(PackageInfo _app, int _version) {
1457 app = _app;
1458 storedAppVersion = _version;
1459 }
1460 }
1461
Christopher Tate44a27902010-01-27 17:15:49 -08001462 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate84725812010-02-04 15:52:40 -08001463 long restoreSetToken, PackageInfo targetPackage) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001464 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001465 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001466 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001467 mTargetPackage = targetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001468
1469 try {
1470 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1471 } catch (RemoteException e) {
1472 // can't happen; the transport is local
1473 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001474 }
1475
Christopher Tatedf01dea2009-06-09 20:45:02 -07001476 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001478 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001479 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
1480 + " mTargetPackage=" + mTargetPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001481 /**
1482 * Restore sequence:
1483 *
Dan Egnorefe52642009-06-24 00:16:33 -07001484 * 1. get the restore set description for our identity
1485 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001486 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001487 * 3. for each app in the restore queue:
1488 * 3.a. clear the app data
1489 * 3.b. get the restore data for the app from the transport
1490 * 3.c. launch the backup agent for the app
1491 * 3.d. agent.doRestore() with the data from the server
1492 * 3.e. unbind the agent [and kill the app?]
1493 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001494 *
1495 * On errors, we try our best to recover and move on to the next
1496 * application, but if necessary we abort the whole operation --
Christopher Tate84725812010-02-04 15:52:40 -08001497 * the user is waiting, after all.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001498 */
1499
Christopher Tate7d562ec2009-06-25 18:03:43 -07001500 int error = -1; // assume error
1501
Dan Egnorefe52642009-06-24 00:16:33 -07001502 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001503 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001504 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001505 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001506
Dan Egnorefe52642009-06-24 00:16:33 -07001507 // Get the list of all packages which have backup enabled.
1508 // (Include the Package Manager metadata pseudo-package first.)
1509 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1510 PackageInfo omPackage = new PackageInfo();
1511 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1512 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001513
Dan Egnorefe52642009-06-24 00:16:33 -07001514 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001515 if (mTargetPackage == null) {
1516 restorePackages.addAll(agentPackages);
1517 } else {
1518 // Just one package to attempt restore of
1519 restorePackages.add(mTargetPackage);
1520 }
Dan Egnorefe52642009-06-24 00:16:33 -07001521
Christopher Tate7d562ec2009-06-25 18:03:43 -07001522 // let the observer know that we're running
1523 if (mObserver != null) {
1524 try {
1525 // !!! TODO: get an actual count from the transport after
1526 // its startRestore() runs?
1527 mObserver.restoreStarting(restorePackages.size());
1528 } catch (RemoteException e) {
1529 Log.d(TAG, "Restore observer died at restoreStarting");
1530 mObserver = null;
1531 }
1532 }
1533
Dan Egnor01445162009-09-21 17:04:05 -07001534 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1535 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001536 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001537 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001538 return;
1539 }
1540
1541 String packageName = mTransport.nextRestorePackage();
1542 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001543 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001544 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001545 return;
1546 } else if (packageName.equals("")) {
1547 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001548 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001549 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001550 return;
1551 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1552 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1553 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001554 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001555 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001556 return;
1557 }
1558
1559 // Pull the Package Manager metadata from the restore set first
1560 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1561 mPackageManager, agentPackages);
1562 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1563
Christopher Tate8c032472009-07-02 14:28:47 -07001564 // Verify that the backup set includes metadata. If not, we can't do
1565 // signature/version verification etc, so we simply do not proceed with
1566 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001567 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001568 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001569 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001570 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001571 return;
1572 }
1573
Christopher Tate7d562ec2009-06-25 18:03:43 -07001574 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001575 for (;;) {
1576 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001577
Dan Egnorefe52642009-06-24 00:16:33 -07001578 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001579 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001581 return;
1582 } else if (packageName.equals("")) {
1583 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001584 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001585
Christopher Tate7d562ec2009-06-25 18:03:43 -07001586 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001587 try {
1588 mObserver.onUpdate(count);
1589 } catch (RemoteException e) {
1590 Log.d(TAG, "Restore observer died in onUpdate");
1591 mObserver = null;
1592 }
1593 }
1594
Dan Egnorefe52642009-06-24 00:16:33 -07001595 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1596 if (metaInfo == null) {
1597 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001598 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001600 continue;
1601 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001602
Dan Egnorbb9001c2009-07-27 12:20:13 -07001603 PackageInfo packageInfo;
1604 try {
1605 int flags = PackageManager.GET_SIGNATURES;
1606 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1607 } catch (NameNotFoundException e) {
1608 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001610 "Package missing on device");
1611 continue;
1612 }
1613
Dan Egnorefe52642009-06-24 00:16:33 -07001614 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001615 String message = "Version " + metaInfo.versionCode
1616 + " > installed version " + packageInfo.versionCode;
1617 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001618 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001619 continue;
1620 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001621
Christopher Tate78dd4a72009-11-04 11:49:08 -08001622 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001623 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001624 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001626 continue;
1627 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628
Dan Egnorefe52642009-06-24 00:16:33 -07001629 if (DEBUG) Log.v(TAG, "Package " + packageName
1630 + " restore version [" + metaInfo.versionCode
1631 + "] is compatible with installed version ["
1632 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001633
Christopher Tate5e1ab332009-09-01 20:32:49 -07001634 // Now perform the actual restore: first clear the app's data
1635 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001636 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001637
1638 // Then set up and bind the agent (with a restricted Application object
1639 // unless the application says otherwise)
1640 boolean useRealApp = (packageInfo.applicationInfo.flags
1641 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1642 if (DEBUG && useRealApp) {
1643 Log.v(TAG, "agent requires real Application subclass for restore");
1644 }
Dan Egnorefe52642009-06-24 00:16:33 -07001645 IBackupAgent agent = bindToAgentSynchronous(
1646 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001647 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1648 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001649 if (agent == null) {
1650 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001651 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001652 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001653 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001654 }
1655
Christopher Tate5e1ab332009-09-01 20:32:49 -07001656 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001657 try {
1658 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001659 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001660 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001661 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001662 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001663
1664 // The agent was probably running with a stub Application object,
1665 // which isn't a valid run mode for the main app logic. Shut
1666 // down the app so that next time it's launched, it gets the
1667 // usual full initialization.
1668 if ((packageInfo.applicationInfo.flags
1669 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1670 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1671 + packageInfo.applicationInfo.processName);
1672 mActivityManager.killApplicationProcess(
1673 packageInfo.applicationInfo.processName,
1674 packageInfo.applicationInfo.uid);
1675 }
Dan Egnorefe52642009-06-24 00:16:33 -07001676 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001677 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001678
1679 // if we get this far, report success to the observer
1680 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001681 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001682 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001683 } catch (Exception e) {
1684 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001685 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001686 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1687
Dan Egnorefe52642009-06-24 00:16:33 -07001688 try {
1689 mTransport.finishRestore();
1690 } catch (RemoteException e) {
1691 Log.e(TAG, "Error finishing restore", e);
1692 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001693
1694 if (mObserver != null) {
1695 try {
1696 mObserver.restoreFinished(error);
1697 } catch (RemoteException e) {
1698 Log.d(TAG, "Restore observer died at restoreFinished");
1699 }
1700 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001701
Christopher Tate84725812010-02-04 15:52:40 -08001702 // If this was a restoreAll operation, record that this was our
1703 // ancestral dataset
1704 if (mTargetPackage == null) {
1705 mAncestralToken = mToken;
1706 writeRestoreTokens();
1707 }
1708
Christopher Tateb6787f22009-07-02 17:40:45 -07001709 // done; we can finally release the wakelock
1710 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001711 }
1712 }
1713
Dan Egnorefe52642009-06-24 00:16:33 -07001714 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1715 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001716 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001717 final String packageName = app.packageName;
1718
Dan Egnorbb9001c2009-07-27 12:20:13 -07001719 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001720
Christopher Tate0749dcd2009-08-13 15:13:03 -07001721 // Don't restore to unprivileged packages
1722 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1723 packageName) != PackageManager.PERMISSION_GRANTED) {
1724 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1725 }
1726
Christopher Tatec7b31e32009-06-10 15:49:30 -07001727 // !!! TODO: get the dirs from the transport
1728 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001729 File newStateName = new File(mStateDir, packageName + ".new");
1730 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001731
Dan Egnorbb9001c2009-07-27 12:20:13 -07001732 ParcelFileDescriptor backupData = null;
1733 ParcelFileDescriptor newState = null;
1734
Christopher Tate44a27902010-01-27 17:15:49 -08001735 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001736 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001737 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001738 backupData = ParcelFileDescriptor.open(backupDataName,
1739 ParcelFileDescriptor.MODE_READ_WRITE |
1740 ParcelFileDescriptor.MODE_CREATE |
1741 ParcelFileDescriptor.MODE_TRUNCATE);
1742
Dan Egnor01445162009-09-21 17:04:05 -07001743 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001744 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001745 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001746 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001747 }
1748
1749 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001750 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001751 backupData = ParcelFileDescriptor.open(backupDataName,
1752 ParcelFileDescriptor.MODE_READ_ONLY);
1753
Dan Egnorbb9001c2009-07-27 12:20:13 -07001754 newState = ParcelFileDescriptor.open(newStateName,
1755 ParcelFileDescriptor.MODE_READ_WRITE |
1756 ParcelFileDescriptor.MODE_CREATE |
1757 ParcelFileDescriptor.MODE_TRUNCATE);
1758
Christopher Tate44a27902010-01-27 17:15:49 -08001759 // Kick off the restore, checking for hung agents
1760 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1761 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1762 boolean success = waitUntilOperationComplete(token);
1763
1764 if (!success) {
1765 throw new RuntimeException("restore timeout");
1766 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001767
1768 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001769 //
1770 // !!! TODO: the restored data should be migrated on the server
1771 // side into the current dataset. In that case the new state file
1772 // we just created would reflect the data already extant in the
1773 // backend, so there'd be nothing more to do. Until that happens,
1774 // however, we need to make sure that we record the data to the
1775 // current backend dataset. (Yes, this means shipping the data over
1776 // the wire in both directions. That's bad, but consistency comes
1777 // first, then efficiency.) Once we introduce server-side data
1778 // migration to the newly-restored device's dataset, we will change
1779 // the following from a discard of the newly-written state to the
1780 // "correct" operation of renaming into the canonical state blob.
1781 newStateName.delete(); // TODO: remove; see above comment
1782 //newStateName.renameTo(savedStateName); // TODO: replace with this
1783
Dan Egnorbb9001c2009-07-27 12:20:13 -07001784 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001785 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001786 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001787 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001788 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001789
Christopher Tate96733042009-07-20 14:49:13 -07001790 // If the agent fails restore, it might have put the app's data
1791 // into an incoherent state. For consistency we wipe its data
1792 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001793 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001794 } finally {
1795 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001796 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1797 try { if (newState != null) newState.close(); } catch (IOException e) {}
1798 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001799 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001800 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001801 }
1802 }
1803
Christopher Tate44a27902010-01-27 17:15:49 -08001804 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001805 IBackupTransport mTransport;
1806 PackageInfo mPackage;
1807
Christopher Tate44a27902010-01-27 17:15:49 -08001808 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001809 mTransport = transport;
1810 mPackage = packageInfo;
1811 }
1812
Christopher Tateee0e78a2009-07-02 11:17:03 -07001813 public void run() {
1814 try {
1815 // Clear the on-device backup state to ensure a full backup next time
1816 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1817 File stateFile = new File(stateDir, mPackage.packageName);
1818 stateFile.delete();
1819
1820 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001821 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001822 mTransport.clearBackupData(mPackage);
1823 } catch (RemoteException e) {
1824 // can't happen; the transport is local
1825 } finally {
1826 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001827 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001828 mTransport.finishBackup();
1829 } catch (RemoteException e) {
1830 // can't happen; the transport is local
1831 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001832
1833 // Last but not least, release the cpu
1834 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001835 }
1836 }
1837 }
1838
Christopher Tate44a27902010-01-27 17:15:49 -08001839 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001840 HashSet<String> mQueue;
1841
Christopher Tate44a27902010-01-27 17:15:49 -08001842 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001843 mQueue = transportNames;
1844 }
1845
Christopher Tate4cc86e12009-09-21 19:36:51 -07001846 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001847 try {
1848 for (String transportName : mQueue) {
1849 IBackupTransport transport = getTransport(transportName);
1850 if (transport == null) {
1851 Log.e(TAG, "Requested init for " + transportName + " but not found");
1852 continue;
1853 }
1854
Dan Egnor726247c2009-09-29 19:12:31 -07001855 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001856 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001857 long startRealtime = SystemClock.elapsedRealtime();
1858 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001859
Christopher Tate4cc86e12009-09-21 19:36:51 -07001860 if (status == BackupConstants.TRANSPORT_OK) {
1861 status = transport.finishBackup();
1862 }
1863
1864 // Okay, the wipe really happened. Clean up our local bookkeeping.
1865 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001866 Log.i(TAG, "Device init successful");
1867 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001868 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001869 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001870 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001871 synchronized (mQueueLock) {
1872 recordInitPendingLocked(false, transportName);
1873 }
Dan Egnor726247c2009-09-29 19:12:31 -07001874 } else {
1875 // If this didn't work, requeue this one and try again
1876 // after a suitable interval
1877 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001878 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001879 synchronized (mQueueLock) {
1880 recordInitPendingLocked(true, transportName);
1881 }
1882 // do this via another alarm to make sure of the wakelock states
1883 long delay = transport.requestBackupTime();
1884 if (DEBUG) Log.w(TAG, "init failed on "
1885 + transportName + " resched in " + delay);
1886 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1887 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001888 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001889 }
1890 } catch (RemoteException e) {
1891 // can't happen; the transports are local
1892 } catch (Exception e) {
1893 Log.e(TAG, "Unexpected error performing init", e);
1894 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001895 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001896 mWakelock.release();
1897 }
1898 }
1899 }
1900
Christopher Tatedf01dea2009-06-09 20:45:02 -07001901
Christopher Tate487529a2009-04-29 14:03:25 -07001902 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001903
Dan Egnor852f8e42009-09-30 11:20:45 -07001904 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001905 // Record that we need a backup pass for the caller. Since multiple callers
1906 // may share a uid, we need to note all candidates within that uid and schedule
1907 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001908 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001909
Christopher Tate63d27002009-06-16 17:16:42 -07001910 // If the caller does not hold the BACKUP permission, it can only request a
1911 // backup of its own data.
1912 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001913 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001914 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1915 targets = mBackupParticipants.get(Binder.getCallingUid());
1916 } else {
1917 // a caller with full permission can ask to back up any participating app
1918 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001919 targets = new HashSet<ApplicationInfo>();
1920 int N = mBackupParticipants.size();
1921 for (int i = 0; i < N; i++) {
1922 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1923 if (s != null) {
1924 targets.addAll(s);
1925 }
1926 }
1927 }
Christopher Tate487529a2009-04-29 14:03:25 -07001928 if (targets != null) {
1929 synchronized (mQueueLock) {
1930 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001931 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001932 // validate the caller-supplied package name against the known set of
1933 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001934 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001935 // Add the caller to the set of pending backups. If there is
1936 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001937 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001938 if (mPendingBackups.put(app, req) == null) {
1939 // Journal this request in case of crash. The put()
1940 // operation returned null when this package was not already
1941 // in the set; we want to avoid touching the disk redundantly.
1942 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001943
Christopher Tate22b60d82009-07-07 16:36:02 -07001944 if (DEBUG) {
1945 int numKeys = mPendingBackups.size();
1946 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1947 for (BackupRequest b : mPendingBackups.values()) {
1948 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1949 }
1950 }
1951 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001952 }
1953 }
Christopher Tate487529a2009-04-29 14:03:25 -07001954 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001955 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001956 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1957 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001958 }
1959 }
Christopher Tate46758122009-05-06 11:22:00 -07001960
Christopher Tatecde87f42009-06-12 12:55:53 -07001961 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001962 RandomAccessFile out = null;
1963 try {
1964 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1965 out = new RandomAccessFile(mJournal, "rws");
1966 out.seek(out.length());
1967 out.writeUTF(str);
1968 } catch (IOException e) {
1969 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1970 mJournal = null;
1971 } finally {
1972 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001973 }
1974 }
1975
Christopher Tateee0e78a2009-07-02 11:17:03 -07001976 // Clear the given package's backup data from the current transport
1977 public void clearBackupData(String packageName) {
1978 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1979 PackageInfo info;
1980 try {
1981 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1982 } catch (NameNotFoundException e) {
1983 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1984 return;
1985 }
1986
1987 // If the caller does not hold the BACKUP permission, it can only request a
1988 // wipe of its own backed-up data.
1989 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001990 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001991 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1992 apps = mBackupParticipants.get(Binder.getCallingUid());
1993 } else {
1994 // a caller with full permission can ask to back up any participating app
1995 // !!! TODO: allow data-clear of ANY app?
1996 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1997 apps = new HashSet<ApplicationInfo>();
1998 int N = mBackupParticipants.size();
1999 for (int i = 0; i < N; i++) {
2000 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2001 if (s != null) {
2002 apps.addAll(s);
2003 }
2004 }
2005 }
2006
2007 // now find the given package in the set of candidate apps
2008 for (ApplicationInfo app : apps) {
2009 if (app.packageName.equals(packageName)) {
2010 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
2011 // found it; fire off the clear request
2012 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002013 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002014 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002015 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2016 new ClearParams(getTransport(mCurrentTransport), info));
2017 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002018 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002019 }
2020 break;
2021 }
2022 }
2023 }
2024
Christopher Tateace7f092009-06-15 18:07:25 -07002025 // Run a backup pass immediately for any applications that have declared
2026 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002027 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002028 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002029
Christopher Tateace7f092009-06-15 18:07:25 -07002030 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002031 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002032 // Because the alarms we are using can jitter, and we want an *immediate*
2033 // backup pass to happen, we restart the timer beginning with "next time,"
2034 // then manually fire the backup trigger intent ourselves.
2035 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002036 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002037 mRunBackupIntent.send();
2038 } catch (PendingIntent.CanceledException e) {
2039 // should never happen
2040 Log.e(TAG, "run-backup intent cancelled!");
2041 }
Christopher Tate46758122009-05-06 11:22:00 -07002042 }
2043 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002044
Christopher Tate8031a3d2009-07-06 16:36:05 -07002045 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002046 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002047 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2048 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002049
Christopher Tate4cc86e12009-09-21 19:36:51 -07002050 Log.i(TAG, "Backup enabled => " + enable);
2051
Christopher Tate6ef58a12009-06-29 14:56:28 -07002052 boolean wasEnabled = mEnabled;
2053 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002054 Settings.Secure.putInt(mContext.getContentResolver(),
2055 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002056 mEnabled = enable;
2057 }
2058
Christopher Tate49401dd2009-07-01 12:34:29 -07002059 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002060 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002061 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002062 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002063 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002064 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002065 if (DEBUG) Log.i(TAG, "Opting out of backup");
2066
Christopher Tateb6787f22009-07-02 17:40:45 -07002067 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002068
2069 // This also constitutes an opt-out, so we wipe any data for
2070 // this device from the backend. We start that process with
2071 // an alarm in order to guarantee wakelock states.
2072 if (wasEnabled && mProvisioned) {
2073 // NOTE: we currently flush every registered transport, not just
2074 // the currently-active one.
2075 HashSet<String> allTransports;
2076 synchronized (mTransports) {
2077 allTransports = new HashSet<String>(mTransports.keySet());
2078 }
2079 // build the set of transports for which we are posting an init
2080 for (String transport : allTransports) {
2081 recordInitPendingLocked(true, transport);
2082 }
2083 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2084 mRunInitIntent);
2085 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002086 }
2087 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002088 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002089
Christopher Tatecce9da52010-02-03 15:11:15 -08002090 // Enable/disable automatic restore of app data at install time
2091 public void setAutoRestore(boolean doAutoRestore) {
2092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2093 "setBackupEnabled");
2094
2095 Log.i(TAG, "Auto restore => " + doAutoRestore);
2096
2097 synchronized (this) {
2098 Settings.Secure.putInt(mContext.getContentResolver(),
2099 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2100 mAutoRestore = doAutoRestore;
2101 }
2102 }
2103
Christopher Tate8031a3d2009-07-06 16:36:05 -07002104 // Mark the backup service as having been provisioned
2105 public void setBackupProvisioned(boolean available) {
2106 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2107 "setBackupProvisioned");
2108
2109 boolean wasProvisioned = mProvisioned;
2110 synchronized (this) {
2111 Settings.Secure.putInt(mContext.getContentResolver(),
2112 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2113 mProvisioned = available;
2114 }
2115
2116 synchronized (mQueueLock) {
2117 if (available && !wasProvisioned && mEnabled) {
2118 // we're now good to go, so start the backup alarms
2119 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2120 } else if (!available) {
2121 // No longer enabled, so stop running backups
2122 Log.w(TAG, "Backup service no longer provisioned");
2123 mAlarmManager.cancel(mRunBackupIntent);
2124 }
2125 }
2126 }
2127
2128 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002129 // We used to use setInexactRepeating(), but that may be linked to
2130 // backups running at :00 more often than not, creating load spikes.
2131 // Schedule at an exact time for now, and also add a bit of "fuzz".
2132
2133 Random random = new Random();
2134 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2135 random.nextInt(FUZZ_MILLIS);
2136 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2137 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002138 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002139 }
2140
Christopher Tate6ef58a12009-06-29 14:56:28 -07002141 // Report whether the backup mechanism is currently enabled
2142 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002143 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002144 return mEnabled; // no need to synchronize just to read it
2145 }
2146
Christopher Tate91717492009-06-26 21:07:13 -07002147 // Report the name of the currently active transport
2148 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002150 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002151 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002152 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002153 }
2154
Christopher Tate91717492009-06-26 21:07:13 -07002155 // Report all known, available backup transports
2156 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002158
Christopher Tate91717492009-06-26 21:07:13 -07002159 String[] list = null;
2160 ArrayList<String> known = new ArrayList<String>();
2161 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2162 if (entry.getValue() != null) {
2163 known.add(entry.getKey());
2164 }
2165 }
2166
2167 if (known.size() > 0) {
2168 list = new String[known.size()];
2169 known.toArray(list);
2170 }
2171 return list;
2172 }
2173
2174 // Select which transport to use for the next backup operation. If the given
2175 // name is not one of the available transports, no action is taken and the method
2176 // returns null.
2177 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002179
2180 synchronized (mTransports) {
2181 String prevTransport = null;
2182 if (mTransports.get(transport) != null) {
2183 prevTransport = mCurrentTransport;
2184 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002185 Settings.Secure.putString(mContext.getContentResolver(),
2186 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002187 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2188 + " returning " + prevTransport);
2189 } else {
2190 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2191 }
2192 return prevTransport;
2193 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002194 }
2195
2196 // Callback: a requested backup agent has been instantiated. This should only
2197 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002198 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002199 synchronized(mAgentConnectLock) {
2200 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2201 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2202 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2203 mConnectedAgent = agent;
2204 mConnecting = false;
2205 } else {
2206 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2207 + " claiming agent connected");
2208 }
2209 mAgentConnectLock.notifyAll();
2210 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002211 }
2212
2213 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2214 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002215 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002216 public void agentDisconnected(String packageName) {
2217 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002218 synchronized(mAgentConnectLock) {
2219 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2220 mConnectedAgent = null;
2221 mConnecting = false;
2222 } else {
2223 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2224 + " claiming agent disconnected");
2225 }
2226 mAgentConnectLock.notifyAll();
2227 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002228 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002229
Christopher Tate8c850b72009-06-07 19:33:20 -07002230 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002231 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002233
2234 synchronized(this) {
2235 if (mActiveRestoreSession != null) {
2236 Log.d(TAG, "Restore session requested but one already active");
2237 return null;
2238 }
Christopher Tate80202c82010-01-25 19:37:47 -08002239 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002240 }
2241 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002242 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002243
Christopher Tate44a27902010-01-27 17:15:49 -08002244 // Note that a currently-active backup agent has notified us that it has
2245 // completed the given outstanding asynchronous backup/restore operation.
2246 public void opComplete(int token) {
2247 synchronized (mCurrentOpLock) {
2248 if (DEBUG) Log.v(TAG, "opComplete: " + token);
2249 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2250 mCurrentOpLock.notifyAll();
2251 }
2252 }
2253
Christopher Tate9b3905c2009-06-08 15:24:01 -07002254 // ----- Restore session -----
2255
Christopher Tate80202c82010-01-25 19:37:47 -08002256 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002257 private static final String TAG = "RestoreSession";
2258
Christopher Tate9b3905c2009-06-08 15:24:01 -07002259 private IBackupTransport mRestoreTransport = null;
2260 RestoreSet[] mRestoreSets = null;
2261
Christopher Tate80202c82010-01-25 19:37:47 -08002262 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002263 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002264 }
2265
2266 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002267 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002269 "getAvailableRestoreSets");
2270
Christopher Tatef68eb502009-06-16 11:02:01 -07002271 try {
Christopher Tate43383042009-07-13 15:17:13 -07002272 if (mRestoreTransport == null) {
2273 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002274 return null;
2275 }
2276 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002277 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002278 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002279 }
2280 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002281 } catch (Exception e) {
2282 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2283 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002284 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002285 }
2286
Christopher Tate84725812010-02-04 15:52:40 -08002287 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2289 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002290
Christopher Tatef2c321a2009-08-10 15:43:36 -07002291 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2292 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002293
Dan Egnor0084da52009-07-29 12:57:16 -07002294 if (mRestoreTransport == null || mRestoreSets == null) {
2295 Log.e(TAG, "Ignoring performRestore() with no restore set");
2296 return -1;
2297 }
2298
Christopher Tate21ab6a52009-09-24 18:01:46 -07002299 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002300 for (int i = 0; i < mRestoreSets.length; i++) {
2301 if (token == mRestoreSets[i].token) {
2302 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002303 mWakelock.acquire();
2304 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2305 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2306 mBackupHandler.sendMessage(msg);
2307 Binder.restoreCallingIdentity(oldId);
2308 return 0;
2309 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002310 }
2311 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002312
2313 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002314 return -1;
2315 }
2316
Christopher Tate84725812010-02-04 15:52:40 -08002317 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
2318 if (DEBUG) Log.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
2319
2320 PackageInfo app = null;
2321 try {
2322 app = mPackageManager.getPackageInfo(packageName, 0);
2323 } catch (NameNotFoundException nnf) {
2324 Log.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2325 return -1;
2326 }
2327
2328 // If the caller is not privileged and is not coming from the target
2329 // app's uid, throw a permission exception back to the caller.
2330 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2331 Binder.getCallingPid(), Binder.getCallingUid());
2332 if ((perm == PackageManager.PERMISSION_DENIED) &&
2333 (app.applicationInfo.uid != Binder.getCallingUid())) {
2334 Log.w(TAG, "restorePackage: bad packageName=" + packageName
2335 + " or calling uid=" + Binder.getCallingUid());
2336 throw new SecurityException("No permission to restore other packages");
2337 }
2338
2339 // So far so good; we're allowed to try to restore this package. Now
2340 // check whether there is data for it in the current dataset, falling back
2341 // to the ancestral dataset if not.
2342 long token = mAncestralToken;
2343 synchronized (mQueueLock) {
2344 if (mEverStoredApps.contains(packageName)) {
2345 token = mCurrentToken;
2346 }
2347 }
2348
2349 // If we didn't come up with a place to look -- no ancestral dataset and
2350 // the app has never been backed up from this device -- there's nothing
2351 // to do but return failure.
2352 if (token == 0) {
2353 return -1;
2354 }
2355
2356 // Ready to go: enqueue the restore request and claim success
2357 long oldId = Binder.clearCallingIdentity();
2358 mWakelock.acquire();
2359 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2360 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app);
2361 mBackupHandler.sendMessage(msg);
2362 Binder.restoreCallingIdentity(oldId);
2363 return 0;
2364 }
2365
Dan Egnor0084da52009-07-29 12:57:16 -07002366 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002368 "endRestoreSession");
2369
Dan Egnor0084da52009-07-29 12:57:16 -07002370 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002371
Dan Egnor0084da52009-07-29 12:57:16 -07002372 synchronized (this) {
2373 try {
2374 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2375 } catch (Exception e) {
2376 Log.e(TAG, "Error in finishRestore", e);
2377 } finally {
2378 mRestoreTransport = null;
2379 }
2380 }
2381
2382 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002383 if (BackupManagerService.this.mActiveRestoreSession == this) {
2384 BackupManagerService.this.mActiveRestoreSession = null;
2385 } else {
2386 Log.e(TAG, "ending non-current restore session");
2387 }
2388 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002389 }
2390 }
2391
Christopher Tate043dadc2009-06-02 16:11:00 -07002392
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002393 @Override
2394 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2395 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002396 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002397 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002398 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tate55f931a2009-09-29 17:17:34 -07002399 pw.println("Last backup pass: " + mLastBackupPass
2400 + " (now = " + System.currentTimeMillis() + ')');
2401 pw.println(" next scheduled: " + mNextBackupPass);
2402
Christopher Tate91717492009-06-26 21:07:13 -07002403 pw.println("Available transports:");
2404 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002405 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2406 try {
2407 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2408 for (File f : dir.listFiles()) {
2409 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2410 }
2411 } catch (RemoteException e) {
2412 Log.e(TAG, "Error in transportDirName()", e);
2413 pw.println(" Error: " + e);
2414 }
Christopher Tate91717492009-06-26 21:07:13 -07002415 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002416
2417 pw.println("Pending init: " + mPendingInits.size());
2418 for (String s : mPendingInits) {
2419 pw.println(" " + s);
2420 }
2421
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002422 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002423 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002424 for (int i=0; i<N; i++) {
2425 int uid = mBackupParticipants.keyAt(i);
2426 pw.print(" uid: ");
2427 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002428 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2429 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002430 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002431 }
2432 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002433
Christopher Tate73e02522009-07-15 14:18:26 -07002434 pw.println("Ever backed up: " + mEverStoredApps.size());
2435 for (String pkg : mEverStoredApps) {
2436 pw.println(" " + pkg);
2437 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002438
2439 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002440 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002441 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002442 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002443 }
2444 }
Christopher Tate487529a2009-04-29 14:03:25 -07002445}