blob: a7a6df515faacba0246f75a92f990b8a19b3dc0a [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 Tateb49ceb32010-02-08 16:22:24 -080079import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81class BackupManagerService extends IBackupManager.Stub {
82 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070083 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070084
Christopher Tate49401dd2009-07-01 12:34:29 -070085 // How often we perform a backup pass. Privileged external callers can
86 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070087 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070088
Dan Egnorc1c49c02009-10-30 17:35:39 -070089 // Random variation in backup scheduling time to avoid server load spikes
90 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
91
Christopher Tate8031a3d2009-07-06 16:36:05 -070092 // The amount of time between the initial provisioning of the device and
93 // the first backup pass.
94 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
95
Christopher Tate4cc86e12009-09-21 19:36:51 -070096 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
97 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
98 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070099 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700100 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700101 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700102 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700103 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate44a27902010-01-27 17:15:49 -0800104 private static final int MSG_TIMEOUT = 6;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700105
106 // Timeout interval for deciding that a bind or clear-data has taken too long
107 static final long TIMEOUT_INTERVAL = 10 * 1000;
108
Christopher Tate44a27902010-01-27 17:15:49 -0800109 // Timeout intervals for agent backup & restore operations
110 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
111 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
112
Christopher Tate487529a2009-04-29 14:03:25 -0700113 private Context mContext;
114 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700115 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700116 private PowerManager mPowerManager;
117 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800118 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700119
Christopher Tate73e02522009-07-15 14:18:26 -0700120 boolean mEnabled; // access to this is synchronized on 'this'
121 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800122 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700123 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800124 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
125 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700126 PendingIntent mRunBackupIntent, mRunInitIntent;
127 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700128 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700129 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700130 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700131 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700132 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700133 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700134 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700135
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 BackupRequest(ApplicationInfo app, boolean isFull) {
137 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700138 fullBackup = isFull;
139 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700140
141 public String toString() {
142 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
143 }
Christopher Tate46758122009-05-06 11:22:00 -0700144 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400145 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700146 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700147 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700148
149 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700150 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700151
152 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700153 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700154
Christopher Tate043dadc2009-06-02 16:11:00 -0700155 // The thread performing the sequence of queued backups binds to each app's agent
156 // in succession. Bind notifications are asynchronously delivered through the
157 // Activity Manager; use this lock object to signal when a requested binding has
158 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700159 final Object mAgentConnectLock = new Object();
160 IBackupAgent mConnectedAgent;
161 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700162 volatile long mLastBackupPass;
163 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700164
Christopher Tate55f931a2009-09-29 17:17:34 -0700165 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700166 final Object mClearDataLock = new Object();
167 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700168
Christopher Tate91717492009-06-26 21:07:13 -0700169 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700170 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700171 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700172 String mCurrentTransport;
173 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800174 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700175
Christopher Tate73e02522009-07-15 14:18:26 -0700176 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700177 public IBackupTransport transport;
178 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700179 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800180 public PackageInfo pkgInfo;
181
182 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
183 long _token, PackageInfo _pkg) {
184 transport = _transport;
185 observer = _obs;
186 token = _token;
187 pkgInfo = _pkg;
188 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700189
Dan Egnor156411d2009-06-26 13:20:02 -0700190 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700191 transport = _transport;
192 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700193 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800194 pkgInfo = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700195 }
196 }
197
Christopher Tate73e02522009-07-15 14:18:26 -0700198 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700199 public IBackupTransport transport;
200 public PackageInfo packageInfo;
201
202 ClearParams(IBackupTransport _transport, PackageInfo _info) {
203 transport = _transport;
204 packageInfo = _info;
205 }
206 }
207
Christopher Tate44a27902010-01-27 17:15:49 -0800208 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
209 // token is the index of the entry in the pending-operations list.
210 static final int OP_PENDING = 0;
211 static final int OP_ACKNOWLEDGED = 1;
212 static final int OP_TIMEOUT = -1;
213
214 final SparseIntArray mCurrentOperations = new SparseIntArray();
215 final Object mCurrentOpLock = new Object();
216 final Random mTokenGenerator = new Random();
217
Christopher Tate5cb400b2009-06-25 16:03:14 -0700218 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700219 File mBaseStateDir;
220 File mDataDir;
221 File mJournalDir;
222 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700223
Christopher Tate84725812010-02-04 15:52:40 -0800224 // Keep a log of all the apps we've ever backed up, and what the
225 // dataset tokens are for both the current backup dataset and
226 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700227 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700228 HashSet<String> mEverStoredApps = new HashSet<String>();
229
Christopher Tateb49ceb32010-02-08 16:22:24 -0800230 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800231 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800232 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800233 long mAncestralToken = 0;
234 long mCurrentToken = 0;
235
Christopher Tate4cc86e12009-09-21 19:36:51 -0700236 // Persistently track the need to do a full init
237 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
238 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700239
Christopher Tate44a27902010-01-27 17:15:49 -0800240 // ----- Asynchronous backup/restore handler thread -----
241
242 private class BackupHandler extends Handler {
243 public BackupHandler(Looper looper) {
244 super(looper);
245 }
246
247 public void handleMessage(Message msg) {
248
249 switch (msg.what) {
250 case MSG_RUN_BACKUP:
251 {
252 mLastBackupPass = System.currentTimeMillis();
253 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
254
255 IBackupTransport transport = getTransport(mCurrentTransport);
256 if (transport == null) {
257 Log.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800258 mWakelock.release();
259 break;
260 }
261
262 // snapshot the pending-backup set and work on that
263 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800264 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800265 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800266 // Do we have any work to do? Construct the work queue
267 // then release the synchronization lock to actually run
268 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800269 if (mPendingBackups.size() > 0) {
270 for (BackupRequest b: mPendingBackups.values()) {
271 queue.add(b);
272 }
273 if (DEBUG) Log.v(TAG, "clearing pending backups");
274 mPendingBackups.clear();
275
276 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800277 mJournal = null;
278
Christopher Tate44a27902010-01-27 17:15:49 -0800279 }
280 }
Christopher Tatec61da312010-02-05 10:41:27 -0800281
282 if (queue.size() > 0) {
283 // At this point, we have started a new journal file, and the old
284 // file identity is being passed to the backup processing thread.
285 // When it completes successfully, that old journal file will be
286 // deleted. If we crash prior to that, the old journal is parsed
287 // at next boot and the journaled requests fulfilled.
288 (new PerformBackupTask(transport, queue, oldJournal)).run();
289 } else {
290 Log.v(TAG, "Backup requested but nothing pending");
291 mWakelock.release();
292 }
Christopher Tate44a27902010-01-27 17:15:49 -0800293 break;
294 }
295
296 case MSG_RUN_FULL_BACKUP:
297 break;
298
299 case MSG_RUN_RESTORE:
300 {
301 RestoreParams params = (RestoreParams)msg.obj;
302 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
303 (new PerformRestoreTask(params.transport, params.observer,
Christopher Tate84725812010-02-04 15:52:40 -0800304 params.token, params.pkgInfo)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800305 break;
306 }
307
308 case MSG_RUN_CLEAR:
309 {
310 ClearParams params = (ClearParams)msg.obj;
311 (new PerformClearTask(params.transport, params.packageInfo)).run();
312 break;
313 }
314
315 case MSG_RUN_INITIALIZE:
316 {
317 HashSet<String> queue;
318
319 // Snapshot the pending-init queue and work on that
320 synchronized (mQueueLock) {
321 queue = new HashSet<String>(mPendingInits);
322 mPendingInits.clear();
323 }
324
325 (new PerformInitializeTask(queue)).run();
326 break;
327 }
328
329 case MSG_TIMEOUT:
330 {
331 synchronized (mCurrentOpLock) {
332 final int token = msg.arg1;
333 int state = mCurrentOperations.get(token, OP_TIMEOUT);
334 if (state == OP_PENDING) {
335 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
336 mCurrentOperations.put(token, OP_TIMEOUT);
337 }
338 mCurrentOpLock.notifyAll();
339 }
340 break;
341 }
342 }
343 }
344 }
345
346 // ----- Main service implementation -----
347
Christopher Tate487529a2009-04-29 14:03:25 -0700348 public BackupManagerService(Context context) {
349 mContext = context;
350 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700351 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700352
Christopher Tateb6787f22009-07-02 17:40:45 -0700353 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
354 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
355
Christopher Tate44a27902010-01-27 17:15:49 -0800356 mBackupManagerBinder = asInterface(asBinder());
357
358 // spin up the backup/restore handler thread
359 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
360 mHandlerThread.start();
361 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
362
Christopher Tate22b87872009-05-04 16:41:53 -0700363 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700364 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700365 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700366 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700367 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800368 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
369 Settings.Secure.BACKUP_AUTO_RESTORE, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800370 // If Encrypted file systems is enabled or disabled, this call will return the
371 // correct directory.
372 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
373 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700374 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700375
Christopher Tate4cc86e12009-09-21 19:36:51 -0700376 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700377 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700378 IntentFilter filter = new IntentFilter();
379 filter.addAction(RUN_BACKUP_ACTION);
380 context.registerReceiver(mRunBackupReceiver, filter,
381 android.Manifest.permission.BACKUP, null);
382
383 mRunInitReceiver = new RunInitializeReceiver();
384 filter = new IntentFilter();
385 filter.addAction(RUN_INITIALIZE_ACTION);
386 context.registerReceiver(mRunInitReceiver, filter,
387 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700388
389 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700390 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
391 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
392
Christopher Tate4cc86e12009-09-21 19:36:51 -0700393 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
394 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
395 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
396
Christopher Tatecde87f42009-06-12 12:55:53 -0700397 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700398 mJournalDir = new File(mBaseStateDir, "pending");
399 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700400 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700401
Christopher Tate73e02522009-07-15 14:18:26 -0700402 // Set up the various sorts of package tracking we do
403 initPackageTracking();
404
Christopher Tateabce4e82009-06-18 18:35:32 -0700405 // Build our mapping of uid to backup client services. This implicitly
406 // schedules a backup pass on the Package Manager metadata the first
407 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700408 synchronized (mBackupParticipants) {
409 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700410 }
411
Dan Egnor87a02bc2009-06-17 02:30:10 -0700412 // Set up our transport options and initialize the default transport
413 // TODO: Have transports register themselves somehow?
414 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700415 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700416 ComponentName localName = new ComponentName(context, LocalTransport.class);
417 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700418
Christopher Tate91717492009-06-26 21:07:13 -0700419 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700420 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
421 Settings.Secure.BACKUP_TRANSPORT);
422 if ("".equals(mCurrentTransport)) {
423 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700424 }
Christopher Tate91717492009-06-26 21:07:13 -0700425 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
426
427 // Attach to the Google backup transport. When this comes up, it will set
428 // itself as the current transport because we explicitly reset mCurrentTransport
429 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700430 Intent intent = new Intent().setComponent(new ComponentName(
431 "com.google.android.backup",
432 "com.google.android.backup.BackupTransportService"));
433 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700434
Christopher Tatecde87f42009-06-12 12:55:53 -0700435 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700436 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700437 parseLeftoverJournals();
438
Christopher Tateb6787f22009-07-02 17:40:45 -0700439 // Power management
440 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
441
442 // Start the backup passes going
443 setBackupEnabled(areEnabled);
444 }
445
446 private class RunBackupReceiver extends BroadcastReceiver {
447 public void onReceive(Context context, Intent intent) {
448 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700449 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700450 if (mPendingInits.size() > 0) {
451 // If there are pending init operations, we process those
452 // and then settle into the usual periodic backup schedule.
453 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
454 try {
455 mAlarmManager.cancel(mRunInitIntent);
456 mRunInitIntent.send();
457 } catch (PendingIntent.CanceledException ce) {
458 Log.e(TAG, "Run init intent cancelled");
459 // can't really do more than bail here
460 }
461 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800462 // Don't run backups now if we're disabled or not yet
463 // fully set up.
464 if (mEnabled && mProvisioned) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700465 if (DEBUG) Log.v(TAG, "Running a backup pass");
466
467 // Acquire the wakelock and pass it to the backup thread. it will
468 // be released once backup concludes.
469 mWakelock.acquire();
470
471 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
472 mBackupHandler.sendMessage(msg);
473 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800474 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700475 }
476 }
477 }
478 }
479 }
480 }
481
482 private class RunInitializeReceiver extends BroadcastReceiver {
483 public void onReceive(Context context, Intent intent) {
484 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
485 synchronized (mQueueLock) {
486 if (DEBUG) Log.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700487
488 // Acquire the wakelock and pass it to the init thread. it will
489 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700490 mWakelock.acquire();
491
Christopher Tate4cc86e12009-09-21 19:36:51 -0700492 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700493 mBackupHandler.sendMessage(msg);
494 }
495 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700496 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700497 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700498
Christopher Tate73e02522009-07-15 14:18:26 -0700499 private void initPackageTracking() {
500 if (DEBUG) Log.v(TAG, "Initializing package tracking");
501
Christopher Tate84725812010-02-04 15:52:40 -0800502 // Remember our ancestral dataset
503 mTokenFile = new File(mBaseStateDir, "ancestral");
504 try {
505 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800506 int version = tf.readInt();
507 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
508 mAncestralToken = tf.readLong();
509 mCurrentToken = tf.readLong();
510
511 int numPackages = tf.readInt();
512 if (numPackages >= 0) {
513 mAncestralPackages = new HashSet<String>();
514 for (int i = 0; i < numPackages; i++) {
515 String pkgName = tf.readUTF();
516 mAncestralPackages.add(pkgName);
517 }
518 }
519 }
Christopher Tate84725812010-02-04 15:52:40 -0800520 } catch (IOException e) {
521 Log.w(TAG, "Unable to read token file", e);
522 }
523
Christopher Tatee97e8072009-07-15 16:45:50 -0700524 // Keep a log of what apps we've ever backed up. Because we might have
525 // rebooted in the middle of an operation that was removing something from
526 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700527 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700528 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700529
Christopher Tatee97e8072009-07-15 16:45:50 -0700530 // If we were in the middle of removing something from the ever-backed-up
531 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700532 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700533 if (tempProcessedFile.exists()) {
534 tempProcessedFile.delete();
535 }
536
Dan Egnor852f8e42009-09-30 11:20:45 -0700537 // If there are previous contents, parse them out then start a new
538 // file to continue the recordkeeping.
539 if (mEverStored.exists()) {
540 RandomAccessFile temp = null;
541 RandomAccessFile in = null;
542
543 try {
544 temp = new RandomAccessFile(tempProcessedFile, "rws");
545 in = new RandomAccessFile(mEverStored, "r");
546
547 while (true) {
548 PackageInfo info;
549 String pkg = in.readUTF();
550 try {
551 info = mPackageManager.getPackageInfo(pkg, 0);
552 mEverStoredApps.add(pkg);
553 temp.writeUTF(pkg);
554 if (DEBUG) Log.v(TAG, " + " + pkg);
555 } catch (NameNotFoundException e) {
556 // nope, this package was uninstalled; don't include it
557 if (DEBUG) Log.v(TAG, " - " + pkg);
558 }
559 }
560 } catch (EOFException e) {
561 // Once we've rewritten the backup history log, atomically replace the
562 // old one with the new one then reopen the file for continuing use.
563 if (!tempProcessedFile.renameTo(mEverStored)) {
564 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
565 }
566 } catch (IOException e) {
567 Log.e(TAG, "Error in processed file", e);
568 } finally {
569 try { if (temp != null) temp.close(); } catch (IOException e) {}
570 try { if (in != null) in.close(); } catch (IOException e) {}
571 }
572 }
573
Christopher Tate73e02522009-07-15 14:18:26 -0700574 // Register for broadcasts about package install, etc., so we can
575 // update the provider list.
576 IntentFilter filter = new IntentFilter();
577 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
578 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
579 filter.addDataScheme("package");
580 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800581 // Register for events related to sdcard installation.
582 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800583 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
584 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800585 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700586 }
587
Christopher Tatecde87f42009-06-12 12:55:53 -0700588 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700589 for (File f : mJournalDir.listFiles()) {
590 if (mJournal == null || f.compareTo(mJournal) != 0) {
591 // This isn't the current journal, so it must be a leftover. Read
592 // out the package names mentioned there and schedule them for
593 // backup.
594 RandomAccessFile in = null;
595 try {
596 Log.i(TAG, "Found stale backup journal, scheduling:");
597 in = new RandomAccessFile(f, "r");
598 while (true) {
599 String packageName = in.readUTF();
600 Log.i(TAG, " + " + packageName);
601 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700602 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700603 } catch (EOFException e) {
604 // no more data; we're done
605 } catch (Exception e) {
606 Log.e(TAG, "Can't read " + f, e);
607 } finally {
608 // close/delete the file
609 try { if (in != null) in.close(); } catch (IOException e) {}
610 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700611 }
612 }
613 }
614 }
615
Christopher Tate4cc86e12009-09-21 19:36:51 -0700616 // Maintain persistent state around whether need to do an initialize operation.
617 // Must be called with the queue lock held.
618 void recordInitPendingLocked(boolean isPending, String transportName) {
619 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
620 + " on transport " + transportName);
621 try {
622 IBackupTransport transport = getTransport(transportName);
623 String transportDirName = transport.transportDirName();
624 File stateDir = new File(mBaseStateDir, transportDirName);
625 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
626
627 if (isPending) {
628 // We need an init before we can proceed with sending backup data.
629 // Record that with an entry in our set of pending inits, as well as
630 // journaling it via creation of a sentinel file.
631 mPendingInits.add(transportName);
632 try {
633 (new FileOutputStream(initPendingFile)).close();
634 } catch (IOException ioe) {
635 // Something is badly wrong with our permissions; just try to move on
636 }
637 } else {
638 // No more initialization needed; wipe the journal and reset our state.
639 initPendingFile.delete();
640 mPendingInits.remove(transportName);
641 }
642 } catch (RemoteException e) {
643 // can't happen; the transport is local
644 }
645 }
646
Christopher Tated55e18a2009-09-21 10:12:59 -0700647 // Reset all of our bookkeeping, in response to having been told that
648 // the backend data has been wiped [due to idle expiry, for example],
649 // so we must re-upload all saved settings.
650 void resetBackupState(File stateFileDir) {
651 synchronized (mQueueLock) {
652 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700653 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700654 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700655
Christopher Tate84725812010-02-04 15:52:40 -0800656 mCurrentToken = 0;
657 writeRestoreTokens();
658
Christopher Tated55e18a2009-09-21 10:12:59 -0700659 // Remove all the state files
660 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700661 // ... but don't touch the needs-init sentinel
662 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
663 sf.delete();
664 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700665 }
666
667 // Enqueue a new backup of every participant
668 int N = mBackupParticipants.size();
669 for (int i=0; i<N; i++) {
670 int uid = mBackupParticipants.keyAt(i);
671 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
672 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700673 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700674 }
675 }
676 }
677 }
678
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800679 // Add a transport to our set of available backends. If 'transport' is null, this
680 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700681 private void registerTransport(String name, IBackupTransport transport) {
682 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700683 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800684 if (transport != null) {
685 mTransports.put(name, transport);
686 } else {
687 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800688 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800689 mCurrentTransport = null;
690 }
691 // Nothing further to do in the unregistration case
692 return;
693 }
Christopher Tate91717492009-06-26 21:07:13 -0700694 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700695
696 // If the init sentinel file exists, we need to be sure to perform the init
697 // as soon as practical. We also create the state directory at registration
698 // time to ensure it's present from the outset.
699 try {
700 String transportName = transport.transportDirName();
701 File stateDir = new File(mBaseStateDir, transportName);
702 stateDir.mkdirs();
703
704 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
705 if (initSentinel.exists()) {
706 synchronized (mQueueLock) {
707 mPendingInits.add(transportName);
708
709 // TODO: pick a better starting time than now + 1 minute
710 long delay = 1000 * 60; // one minute, in milliseconds
711 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
712 System.currentTimeMillis() + delay, mRunInitIntent);
713 }
714 }
715 } catch (RemoteException e) {
716 // can't happen, the transport is local
717 }
Christopher Tate91717492009-06-26 21:07:13 -0700718 }
719
Christopher Tate3799bc22009-05-06 16:13:56 -0700720 // ----- Track installation/removal of packages -----
721 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
722 public void onReceive(Context context, Intent intent) {
723 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
724
Christopher Tate3799bc22009-05-06 16:13:56 -0700725 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800726 boolean replacing = false;
727 boolean added = false;
728 Bundle extras = intent.getExtras();
729 String pkgList[] = null;
730 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
731 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
732 Uri uri = intent.getData();
733 if (uri == null) {
734 return;
735 }
736 String pkgName = uri.getSchemeSpecificPart();
737 if (pkgName != null) {
738 pkgList = new String[] { pkgName };
739 }
740 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
741 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800742 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800743 added = true;
744 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800745 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800746 added = false;
747 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
748 }
749 if (pkgList == null || pkgList.length == 0) {
750 return;
751 }
752 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700753 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800754 for (String pkgName : pkgList) {
755 if (replacing) {
756 // The package was just upgraded
757 updatePackageParticipantsLocked(pkgName);
758 } else {
759 // The package was just added
760 addPackageParticipantsLocked(pkgName);
761 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700762 }
763 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800764 } else {
765 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700766 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
767 } else {
768 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800769 for (String pkgName : pkgList) {
770 removePackageParticipantsLocked(pkgName);
771 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700772 }
773 }
774 }
775 }
776 };
777
Dan Egnor87a02bc2009-06-17 02:30:10 -0700778 // ----- Track connection to GoogleBackupTransport service -----
779 ServiceConnection mGoogleConnection = new ServiceConnection() {
780 public void onServiceConnected(ComponentName name, IBinder service) {
781 if (DEBUG) Log.v(TAG, "Connected to Google transport");
782 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700783 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700784 }
785
786 public void onServiceDisconnected(ComponentName name) {
787 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
788 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700789 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700790 }
791 };
792
Christopher Tate181fafa2009-05-14 11:12:14 -0700793 // Add the backup agents in the given package to our set of known backup participants.
794 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700795 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700796 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700797 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700798 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700799 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700800 }
801
Christopher Tate181fafa2009-05-14 11:12:14 -0700802 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700803 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700804 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700805 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
806 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700807 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700808 + " uid=" + p.applicationInfo.uid
809 + " killAfterRestore="
810 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
811 + " restoreNeedsApplication="
812 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
813 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700814 }
815 }
816
Dan Egnorefe52642009-06-24 00:16:33 -0700817 for (PackageInfo pkg : targetPkgs) {
818 if (packageName == null || pkg.packageName.equals(packageName)) {
819 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700820 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700821 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700822 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700823 mBackupParticipants.put(uid, set);
824 }
Dan Egnorefe52642009-06-24 00:16:33 -0700825 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700826
827 // If we've never seen this app before, schedule a backup for it
828 if (!mEverStoredApps.contains(pkg.packageName)) {
829 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
830 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700831 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700832 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700833 }
Christopher Tate487529a2009-04-29 14:03:25 -0700834 }
835 }
836
Christopher Tate6785dd82009-06-18 15:58:25 -0700837 // Remove the given package's entry from our known active set. If
838 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700839 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700840 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700841 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700842 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700843 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700844 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700845 int flags = PackageManager.GET_SIGNATURES;
846 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700847 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700848 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700849 }
850 } else {
851 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700852 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 }
854 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 }
856
Joe Onorato8ad02812009-05-13 01:41:44 -0400857 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700858 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700859 if (DEBUG) {
860 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
861 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700862 for (PackageInfo p : agents) {
863 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700864 }
865 }
Dan Egnorefe52642009-06-24 00:16:33 -0700866 for (PackageInfo pkg : agents) {
867 if (packageName == null || pkg.packageName.equals(packageName)) {
868 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700869 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700870 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700871 // Find the existing entry with the same package name, and remove it.
872 // We can't just remove(app) because the instances are different.
873 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700874 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700875 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700876 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700877 break;
878 }
879 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700880 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700881 mBackupParticipants.delete(uid);
882 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700883 }
884 }
885 }
886 }
887
Christopher Tate181fafa2009-05-14 11:12:14 -0700888 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700889 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700890 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700891 int flags = PackageManager.GET_SIGNATURES;
892 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
893 int N = packages.size();
894 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700895 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700896 try {
897 ApplicationInfo app = pkg.applicationInfo;
898 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800899 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700900 packages.remove(a);
901 }
902 else {
903 // we will need the shared library path, so look that up and store it here
904 app = mPackageManager.getApplicationInfo(pkg.packageName,
905 PackageManager.GET_SHARED_LIBRARY_FILES);
906 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
907 }
908 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700909 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700910 }
911 }
Dan Egnorefe52642009-06-24 00:16:33 -0700912 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700913 }
Christopher Tateaa088442009-06-16 18:25:46 -0700914
Christopher Tate3799bc22009-05-06 16:13:56 -0700915 // Reset the given package's known backup participants. Unlike add/remove, the update
916 // action cannot be passed a null package name.
917 void updatePackageParticipantsLocked(String packageName) {
918 if (packageName == null) {
919 Log.e(TAG, "updatePackageParticipants called with null package name");
920 return;
921 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700922 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700923
924 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700925 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700926 removePackageParticipantsLockedInner(packageName, allApps);
927 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700928 }
929
Christopher Tate84725812010-02-04 15:52:40 -0800930 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -0700931 // backed up at least once
932 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700933 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
934
935 synchronized (mEverStoredApps) {
936 if (!mEverStoredApps.add(packageName)) return;
937
938 RandomAccessFile out = null;
939 try {
940 out = new RandomAccessFile(mEverStored, "rws");
941 out.seek(out.length());
942 out.writeUTF(packageName);
943 } catch (IOException e) {
944 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
945 } finally {
946 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700947 }
948 }
949 }
950
Christopher Tatee97e8072009-07-15 16:45:50 -0700951 // Remove our awareness of having ever backed up the given package
952 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700953 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700954
Dan Egnor852f8e42009-09-30 11:20:45 -0700955 synchronized (mEverStoredApps) {
956 // Rewrite the file and rename to overwrite. If we reboot in the middle,
957 // we'll recognize on initialization time that the package no longer
958 // exists and fix it up then.
959 File tempKnownFile = new File(mBaseStateDir, "processed.new");
960 RandomAccessFile known = null;
961 try {
962 known = new RandomAccessFile(tempKnownFile, "rws");
963 mEverStoredApps.remove(packageName);
964 for (String s : mEverStoredApps) {
965 known.writeUTF(s);
966 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700967 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700968 known.close();
969 known = null;
970 if (!tempKnownFile.renameTo(mEverStored)) {
971 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
972 }
973 } catch (IOException e) {
974 // Bad: we couldn't create the new copy. For safety's sake we
975 // abandon the whole process and remove all what's-backed-up
976 // state entirely, meaning we'll force a backup pass for every
977 // participant on the next boot or [re]install.
978 Log.w(TAG, "Error rewriting " + mEverStored, e);
979 mEverStoredApps.clear();
980 tempKnownFile.delete();
981 mEverStored.delete();
982 } finally {
983 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700984 }
985 }
986 }
987
Christopher Tateb49ceb32010-02-08 16:22:24 -0800988 // Persistently record the current and ancestral backup tokens as well
989 // as the set of packages with data [supposedly] available in the
990 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -0800991 void writeRestoreTokens() {
992 try {
993 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800994
995 // First, the version number of this record, for futureproofing
996 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
997
998 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -0800999 af.writeLong(mAncestralToken);
1000 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001001
1002 // Now write the set of ancestral packages
1003 if (mAncestralPackages == null) {
1004 af.writeInt(-1);
1005 } else {
1006 af.writeInt(mAncestralPackages.size());
1007 if (DEBUG) Log.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
1008 for (String pkgName : mAncestralPackages) {
1009 af.writeUTF(pkgName);
1010 if (DEBUG) Log.v(TAG, " " + pkgName);
1011 }
1012 }
Christopher Tate84725812010-02-04 15:52:40 -08001013 af.close();
1014 } catch (IOException e) {
1015 Log.w(TAG, "Unable to write token file:", e);
1016 }
1017 }
1018
Dan Egnor87a02bc2009-06-17 02:30:10 -07001019 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001020 private IBackupTransport getTransport(String transportName) {
1021 synchronized (mTransports) {
1022 IBackupTransport transport = mTransports.get(transportName);
1023 if (transport == null) {
1024 Log.w(TAG, "Requested unavailable transport: " + transportName);
1025 }
1026 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001027 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001028 }
1029
Christopher Tatedf01dea2009-06-09 20:45:02 -07001030 // fire off a backup agent, blocking until it attaches or times out
1031 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1032 IBackupAgent agent = null;
1033 synchronized(mAgentConnectLock) {
1034 mConnecting = true;
1035 mConnectedAgent = null;
1036 try {
1037 if (mActivityManager.bindBackupAgent(app, mode)) {
1038 Log.d(TAG, "awaiting agent for " + app);
1039
1040 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001041 // only wait 10 seconds for the clear data to happen
1042 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1043 while (mConnecting && mConnectedAgent == null
1044 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001045 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001046 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001047 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001048 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001049 return null;
1050 }
1051 }
1052
1053 // if we timed out with no connect, abort and move on
1054 if (mConnecting == true) {
1055 Log.w(TAG, "Timeout waiting for agent " + app);
1056 return null;
1057 }
1058 agent = mConnectedAgent;
1059 }
1060 } catch (RemoteException e) {
1061 // can't happen
1062 }
1063 }
1064 return agent;
1065 }
1066
Christopher Tatec7b31e32009-06-10 15:49:30 -07001067 // clear an application's data, blocking until the operation completes or times out
1068 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001069 // Don't wipe packages marked allowClearUserData=false
1070 try {
1071 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1072 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1073 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
1074 + packageName);
1075 return;
1076 }
1077 } catch (NameNotFoundException e) {
1078 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
1079 return;
1080 }
1081
Christopher Tatec7b31e32009-06-10 15:49:30 -07001082 ClearDataObserver observer = new ClearDataObserver();
1083
1084 synchronized(mClearDataLock) {
1085 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001086 /* This is causing some critical processes to be killed during setup.
1087 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -07001088 try {
1089 mActivityManager.clearApplicationUserData(packageName, observer);
1090 } catch (RemoteException e) {
1091 // can't happen because the activity manager is in this process
1092 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001093 */
1094 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001095
1096 // only wait 10 seconds for the clear data to happen
1097 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1098 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1099 try {
1100 mClearDataLock.wait(5000);
1101 } catch (InterruptedException e) {
1102 // won't happen, but still.
1103 mClearingData = false;
1104 }
1105 }
1106 }
1107 }
1108
1109 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001110 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001111 synchronized(mClearDataLock) {
1112 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001113 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001114 }
1115 }
1116 }
1117
Christopher Tate44a27902010-01-27 17:15:49 -08001118 // -----
1119 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1120 boolean waitUntilOperationComplete(int token) {
1121 int finalState = OP_PENDING;
1122 synchronized (mCurrentOpLock) {
1123 try {
1124 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1125 try {
1126 mCurrentOpLock.wait();
1127 } catch (InterruptedException e) {}
1128 }
1129 } catch (IndexOutOfBoundsException e) {
1130 // the operation has been mysteriously cleared from our
1131 // bookkeeping -- consider this a success and ignore it.
1132 }
1133 }
1134 mBackupHandler.removeMessages(MSG_TIMEOUT);
1135 if (DEBUG) Log.v(TAG, "operation " + token + " complete: finalState=" + finalState);
1136 return finalState == OP_ACKNOWLEDGED;
1137 }
1138
1139 void prepareOperationTimeout(int token, long interval) {
1140 if (DEBUG) Log.v(TAG, "starting timeout: token=" + token + " interval=" + interval);
1141 mCurrentOperations.put(token, OP_PENDING);
1142 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1143 mBackupHandler.sendMessageDelayed(msg, interval);
1144 }
1145
Christopher Tate043dadc2009-06-02 16:11:00 -07001146 // ----- Back up a set of applications via a worker thread -----
1147
Christopher Tate44a27902010-01-27 17:15:49 -08001148 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001149 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001150 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001151 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001152 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001153 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001154
Christopher Tate44a27902010-01-27 17:15:49 -08001155 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001156 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001157 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001158 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001159 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001160
1161 try {
1162 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1163 } catch (RemoteException e) {
1164 // can't happen; the transport is local
1165 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001166 }
1167
Christopher Tate043dadc2009-06-02 16:11:00 -07001168 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001169 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001170 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001171 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1172
Christopher Tate79588342009-06-30 16:11:49 -07001173 // Backups run at background priority
1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175
Christopher Tate043dadc2009-06-02 16:11:00 -07001176 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001177 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001178
Dan Egnor852f8e42009-09-30 11:20:45 -07001179 // If we haven't stored package manager metadata yet, we must init the transport.
1180 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1181 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1182 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1183 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001184 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001185 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001186 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001187 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001189 Log.e(TAG, "Transport error in initializeDevice()");
1190 }
Dan Egnor01445162009-09-21 17:04:05 -07001191 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001192
1193 // The package manager doesn't have a proper <application> etc, but since
1194 // it's running here in the system process we can just set up its agent
1195 // directly and use a synthetic BackupRequest. We always run this pass
1196 // because it's cheap and this way we guarantee that we don't get out of
1197 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001198 if (status == BackupConstants.TRANSPORT_OK) {
1199 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1200 mPackageManager, allAgentPackages());
1201 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1202 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1203 status = processOneBackup(pmRequest,
1204 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1205 }
Christopher Tate90967f42009-09-20 15:28:33 -07001206
Dan Egnor01445162009-09-21 17:04:05 -07001207 if (status == BackupConstants.TRANSPORT_OK) {
1208 // Now run all the backups in our queue
1209 status = doQueuedBackups(mTransport);
1210 }
1211
1212 if (status == BackupConstants.TRANSPORT_OK) {
1213 // Tell the transport to finish everything it has buffered
1214 status = mTransport.finishBackup();
1215 if (status == BackupConstants.TRANSPORT_OK) {
1216 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001217 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001218 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001219 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001220 Log.e(TAG, "Transport error in finishBackup()");
1221 }
1222 }
1223
Dan Egnor01445162009-09-21 17:04:05 -07001224 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001225 // The backend reports that our dataset has been wiped. We need to
1226 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001227 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001229 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001230 }
1231 } catch (Exception e) {
1232 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001233 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001234 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001235 // If everything actually went through and this is the first time we've
1236 // done a backup, we can now record what the current backup dataset token
1237 // is.
1238 if ((mCurrentToken == 0) && (status != BackupConstants.TRANSPORT_OK)) {
1239 try {
1240 mCurrentToken = mTransport.getCurrentRestoreSet();
1241 } catch (RemoteException e) { /* cannot happen */ }
1242 writeRestoreTokens();
1243 }
1244
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001245 // If things went wrong, we need to re-stage the apps we had expected
1246 // to be backing up in this pass. This journals the package names in
1247 // the current active pending-backup file, not in the we are holding
1248 // here in mJournal.
1249 if (status != BackupConstants.TRANSPORT_OK) {
1250 Log.w(TAG, "Backup pass unsuccessful, restaging");
1251 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001252 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001253 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001254
1255 // We also want to reset the backup schedule based on whatever
1256 // the transport suggests by way of retry/backoff time.
1257 try {
1258 startBackupAlarmsLocked(mTransport.requestBackupTime());
1259 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001260 }
1261
1262 // Either backup was successful, in which case we of course do not need
1263 // this pass's journal any more; or it failed, in which case we just
1264 // re-enqueued all of these packages in the current active journal.
1265 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001266 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001267 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1268 }
1269
Christopher Tatec2af5d32010-02-02 15:18:58 -08001270 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001271 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001272 backupNow();
1273 }
1274
Dan Egnorbb9001c2009-07-27 12:20:13 -07001275 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001276 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001277 }
1278
Dan Egnor01445162009-09-21 17:04:05 -07001279 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001280 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001281 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001282
1283 IBackupAgent agent = null;
1284 int mode = (request.fullBackup)
1285 ? IApplicationThread.BACKUP_MODE_FULL
1286 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1287 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001288 agent = bindToAgentSynchronous(request.appInfo, mode);
1289 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001290 int result = processOneBackup(request, agent, transport);
1291 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001292 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001293 } catch (SecurityException ex) {
1294 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001295 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001296 } finally {
1297 try { // unbind even on timeout, just in case
1298 mActivityManager.unbindBackupAgent(request.appInfo);
1299 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001300 }
1301 }
Dan Egnor01445162009-09-21 17:04:05 -07001302
1303 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001304 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001305
Dan Egnor01445162009-09-21 17:04:05 -07001306 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1307 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001308 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001309 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001310
Dan Egnorbb9001c2009-07-27 12:20:13 -07001311 File savedStateName = new File(mStateDir, packageName);
1312 File backupDataName = new File(mDataDir, packageName + ".data");
1313 File newStateName = new File(mStateDir, packageName + ".new");
1314
1315 ParcelFileDescriptor savedState = null;
1316 ParcelFileDescriptor backupData = null;
1317 ParcelFileDescriptor newState = null;
1318
1319 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001320 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001321 try {
1322 // Look up the package info & signatures. This is first so that if it
1323 // throws an exception, there's no file setup yet that would need to
1324 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001325 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1326 // The metadata 'package' is synthetic
1327 packInfo = new PackageInfo();
1328 packInfo.packageName = packageName;
1329 } else {
1330 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001331 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001332 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001333
Christopher Tatec7b31e32009-06-10 15:49:30 -07001334 // In a full backup, we pass a null ParcelFileDescriptor as
1335 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001336 if (!request.fullBackup) {
1337 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001338 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001339 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1340 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001341
Dan Egnorbb9001c2009-07-27 12:20:13 -07001342 backupData = ParcelFileDescriptor.open(backupDataName,
1343 ParcelFileDescriptor.MODE_READ_WRITE |
1344 ParcelFileDescriptor.MODE_CREATE |
1345 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001346
Dan Egnorbb9001c2009-07-27 12:20:13 -07001347 newState = ParcelFileDescriptor.open(newStateName,
1348 ParcelFileDescriptor.MODE_READ_WRITE |
1349 ParcelFileDescriptor.MODE_CREATE |
1350 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001351
Christopher Tate44a27902010-01-27 17:15:49 -08001352 // Initiate the target's backup pass
1353 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1354 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1355 boolean success = waitUntilOperationComplete(token);
1356
1357 if (!success) {
1358 // timeout -- bail out into the failed-transaction logic
1359 throw new RuntimeException("Backup timeout");
1360 }
1361
Dan Egnorbb9001c2009-07-27 12:20:13 -07001362 logBackupComplete(packageName);
1363 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001364 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001365 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001366 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001367 backupDataName.delete();
1368 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001369 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001370 } finally {
1371 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1372 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1373 try { if (newState != null) newState.close(); } catch (IOException e) {}
1374 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001375 synchronized (mCurrentOpLock) {
1376 mCurrentOperations.clear();
1377 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001378 }
1379
1380 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001381 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 try {
1383 int size = (int) backupDataName.length();
1384 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001385 if (result == BackupConstants.TRANSPORT_OK) {
1386 backupData = ParcelFileDescriptor.open(backupDataName,
1387 ParcelFileDescriptor.MODE_READ_ONLY);
1388 result = transport.performBackup(packInfo, backupData);
1389 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001390
Dan Egnor83861e72009-09-17 16:17:55 -07001391 // TODO - We call finishBackup() for each application backed up, because
1392 // we need to know now whether it succeeded or failed. Instead, we should
1393 // hold off on finishBackup() until the end, which implies holding off on
1394 // renaming *all* the output state files (see below) until that happens.
1395
Dan Egnor01445162009-09-21 17:04:05 -07001396 if (result == BackupConstants.TRANSPORT_OK) {
1397 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001398 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 } else {
1400 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1401 }
1402
1403 // After successful transport, delete the now-stale data
1404 // and juggle the files so that next time we supply the agent
1405 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001406 if (result == BackupConstants.TRANSPORT_OK) {
1407 backupDataName.delete();
1408 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001409 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001410 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001411 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001412 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001413 } catch (Exception e) {
1414 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001415 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001416 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001417 } finally {
1418 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001419 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001420
Dan Egnor01445162009-09-21 17:04:05 -07001421 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001422 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001423 }
1424
Christopher Tatedf01dea2009-06-09 20:45:02 -07001425
1426 // ----- Restore handling -----
1427
Christopher Tate78dd4a72009-11-04 11:49:08 -08001428 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1429 // If the target resides on the system partition, we allow it to restore
1430 // data from the like-named package in a restore set even if the signatures
1431 // do not match. (Unlike general applications, those flashed to the system
1432 // partition will be signed with the device's platform certificate, so on
1433 // different phones the same system app will have different signatures.)
1434 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1435 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1436 return true;
1437 }
1438
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001439 // Allow unsigned apps, but not signed on one device and unsigned on the other
1440 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001441 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001442 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1443 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001444 if ((storedSigs == null || storedSigs.length == 0)
1445 && (deviceSigs == null || deviceSigs.length == 0)) {
1446 return true;
1447 }
1448 if (storedSigs == null || deviceSigs == null) {
1449 return false;
1450 }
1451
Christopher Tateabce4e82009-06-18 18:35:32 -07001452 // !!! TODO: this demands that every stored signature match one
1453 // that is present on device, and does not demand the converse.
1454 // Is this this right policy?
1455 int nStored = storedSigs.length;
1456 int nDevice = deviceSigs.length;
1457
1458 for (int i=0; i < nStored; i++) {
1459 boolean match = false;
1460 for (int j=0; j < nDevice; j++) {
1461 if (storedSigs[i].equals(deviceSigs[j])) {
1462 match = true;
1463 break;
1464 }
1465 }
1466 if (!match) {
1467 return false;
1468 }
1469 }
1470 return true;
1471 }
1472
Christopher Tate44a27902010-01-27 17:15:49 -08001473 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001474 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001475 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001476 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001477 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001478 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001479
Christopher Tate5cbbf562009-06-22 16:44:51 -07001480 class RestoreRequest {
1481 public PackageInfo app;
1482 public int storedAppVersion;
1483
1484 RestoreRequest(PackageInfo _app, int _version) {
1485 app = _app;
1486 storedAppVersion = _version;
1487 }
1488 }
1489
Christopher Tate44a27902010-01-27 17:15:49 -08001490 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate84725812010-02-04 15:52:40 -08001491 long restoreSetToken, PackageInfo targetPackage) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001492 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001493 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001494 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001495 mTargetPackage = targetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001496
1497 try {
1498 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1499 } catch (RemoteException e) {
1500 // can't happen; the transport is local
1501 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001502 }
1503
Christopher Tatedf01dea2009-06-09 20:45:02 -07001504 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001505 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001506 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001507 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
1508 + " mTargetPackage=" + mTargetPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001509 /**
1510 * Restore sequence:
1511 *
Dan Egnorefe52642009-06-24 00:16:33 -07001512 * 1. get the restore set description for our identity
1513 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001514 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001515 * 3. for each app in the restore queue:
1516 * 3.a. clear the app data
1517 * 3.b. get the restore data for the app from the transport
1518 * 3.c. launch the backup agent for the app
1519 * 3.d. agent.doRestore() with the data from the server
1520 * 3.e. unbind the agent [and kill the app?]
1521 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001522 *
1523 * On errors, we try our best to recover and move on to the next
1524 * application, but if necessary we abort the whole operation --
Christopher Tate84725812010-02-04 15:52:40 -08001525 * the user is waiting, after all.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001526 */
1527
Christopher Tateb49ceb32010-02-08 16:22:24 -08001528 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001529 int error = -1; // assume error
1530
Dan Egnorefe52642009-06-24 00:16:33 -07001531 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001532 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001533 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001534 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001535
Dan Egnorefe52642009-06-24 00:16:33 -07001536 // Get the list of all packages which have backup enabled.
1537 // (Include the Package Manager metadata pseudo-package first.)
1538 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1539 PackageInfo omPackage = new PackageInfo();
1540 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1541 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001542
Dan Egnorefe52642009-06-24 00:16:33 -07001543 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001544 if (mTargetPackage == null) {
1545 restorePackages.addAll(agentPackages);
1546 } else {
1547 // Just one package to attempt restore of
1548 restorePackages.add(mTargetPackage);
1549 }
Dan Egnorefe52642009-06-24 00:16:33 -07001550
Christopher Tate7d562ec2009-06-25 18:03:43 -07001551 // let the observer know that we're running
1552 if (mObserver != null) {
1553 try {
1554 // !!! TODO: get an actual count from the transport after
1555 // its startRestore() runs?
1556 mObserver.restoreStarting(restorePackages.size());
1557 } catch (RemoteException e) {
1558 Log.d(TAG, "Restore observer died at restoreStarting");
1559 mObserver = null;
1560 }
1561 }
1562
Dan Egnor01445162009-09-21 17:04:05 -07001563 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1564 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001565 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001566 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001567 return;
1568 }
1569
1570 String packageName = mTransport.nextRestorePackage();
1571 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001572 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001573 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001574 return;
1575 } else if (packageName.equals("")) {
1576 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001577 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001579 return;
1580 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1581 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1582 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001583 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001584 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001585 return;
1586 }
1587
1588 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001589 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001590 mPackageManager, agentPackages);
1591 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1592
Christopher Tate8c032472009-07-02 14:28:47 -07001593 // Verify that the backup set includes metadata. If not, we can't do
1594 // signature/version verification etc, so we simply do not proceed with
1595 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001596 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001597 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001598 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001600 return;
1601 }
1602
Christopher Tate7d562ec2009-06-25 18:03:43 -07001603 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001604 for (;;) {
1605 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606
Dan Egnorefe52642009-06-24 00:16:33 -07001607 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001608 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001610 return;
1611 } else if (packageName.equals("")) {
1612 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001613 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001614
Christopher Tate7d562ec2009-06-25 18:03:43 -07001615 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001616 try {
1617 mObserver.onUpdate(count);
1618 } catch (RemoteException e) {
1619 Log.d(TAG, "Restore observer died in onUpdate");
1620 mObserver = null;
1621 }
1622 }
1623
Dan Egnorefe52642009-06-24 00:16:33 -07001624 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1625 if (metaInfo == null) {
1626 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001627 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001628 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001629 continue;
1630 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001631
Dan Egnorbb9001c2009-07-27 12:20:13 -07001632 PackageInfo packageInfo;
1633 try {
1634 int flags = PackageManager.GET_SIGNATURES;
1635 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1636 } catch (NameNotFoundException e) {
1637 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001638 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 "Package missing on device");
1640 continue;
1641 }
1642
Dan Egnorefe52642009-06-24 00:16:33 -07001643 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001644 String message = "Version " + metaInfo.versionCode
1645 + " > installed version " + packageInfo.versionCode;
1646 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001647 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001648 continue;
1649 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001650
Christopher Tate78dd4a72009-11-04 11:49:08 -08001651 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001652 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001654 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001655 continue;
1656 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001657
Dan Egnorefe52642009-06-24 00:16:33 -07001658 if (DEBUG) Log.v(TAG, "Package " + packageName
1659 + " restore version [" + metaInfo.versionCode
1660 + "] is compatible with installed version ["
1661 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001662
Christopher Tate5e1ab332009-09-01 20:32:49 -07001663 // Now perform the actual restore: first clear the app's data
1664 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001665 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001666
1667 // Then set up and bind the agent (with a restricted Application object
1668 // unless the application says otherwise)
1669 boolean useRealApp = (packageInfo.applicationInfo.flags
1670 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1671 if (DEBUG && useRealApp) {
1672 Log.v(TAG, "agent requires real Application subclass for restore");
1673 }
Dan Egnorefe52642009-06-24 00:16:33 -07001674 IBackupAgent agent = bindToAgentSynchronous(
1675 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001676 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1677 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001678 if (agent == null) {
1679 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001680 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001681 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001682 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001683 }
1684
Christopher Tate5e1ab332009-09-01 20:32:49 -07001685 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001686 try {
1687 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001688 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001689 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001690 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001691 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001692
1693 // The agent was probably running with a stub Application object,
1694 // which isn't a valid run mode for the main app logic. Shut
1695 // down the app so that next time it's launched, it gets the
1696 // usual full initialization.
1697 if ((packageInfo.applicationInfo.flags
1698 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1699 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1700 + packageInfo.applicationInfo.processName);
1701 mActivityManager.killApplicationProcess(
1702 packageInfo.applicationInfo.processName,
1703 packageInfo.applicationInfo.uid);
1704 }
Dan Egnorefe52642009-06-24 00:16:33 -07001705 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001706 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001707
1708 // if we get this far, report success to the observer
1709 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001710 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001711 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001712 } catch (Exception e) {
1713 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001714 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001715 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1716
Dan Egnorefe52642009-06-24 00:16:33 -07001717 try {
1718 mTransport.finishRestore();
1719 } catch (RemoteException e) {
1720 Log.e(TAG, "Error finishing restore", e);
1721 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001722
1723 if (mObserver != null) {
1724 try {
1725 mObserver.restoreFinished(error);
1726 } catch (RemoteException e) {
1727 Log.d(TAG, "Restore observer died at restoreFinished");
1728 }
1729 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001730
Christopher Tate84725812010-02-04 15:52:40 -08001731 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001732 // ancestral dataset, as well as the set of apps that are possibly
1733 // restoreable from the dataset
1734 if (mTargetPackage == null && pmAgent != null) {
1735 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001736 mAncestralToken = mToken;
1737 writeRestoreTokens();
1738 }
1739
Christopher Tateb6787f22009-07-02 17:40:45 -07001740 // done; we can finally release the wakelock
1741 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001742 }
1743 }
1744
Dan Egnorefe52642009-06-24 00:16:33 -07001745 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1746 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001747 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001748 final String packageName = app.packageName;
1749
Dan Egnorbb9001c2009-07-27 12:20:13 -07001750 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001751
Christopher Tatec7b31e32009-06-10 15:49:30 -07001752 // !!! TODO: get the dirs from the transport
1753 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001754 File newStateName = new File(mStateDir, packageName + ".new");
1755 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001756
Dan Egnorbb9001c2009-07-27 12:20:13 -07001757 ParcelFileDescriptor backupData = null;
1758 ParcelFileDescriptor newState = null;
1759
Christopher Tate44a27902010-01-27 17:15:49 -08001760 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001761 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001762 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001763 backupData = ParcelFileDescriptor.open(backupDataName,
1764 ParcelFileDescriptor.MODE_READ_WRITE |
1765 ParcelFileDescriptor.MODE_CREATE |
1766 ParcelFileDescriptor.MODE_TRUNCATE);
1767
Dan Egnor01445162009-09-21 17:04:05 -07001768 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001769 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001770 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001771 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001772 }
1773
1774 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001775 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001776 backupData = ParcelFileDescriptor.open(backupDataName,
1777 ParcelFileDescriptor.MODE_READ_ONLY);
1778
Dan Egnorbb9001c2009-07-27 12:20:13 -07001779 newState = ParcelFileDescriptor.open(newStateName,
1780 ParcelFileDescriptor.MODE_READ_WRITE |
1781 ParcelFileDescriptor.MODE_CREATE |
1782 ParcelFileDescriptor.MODE_TRUNCATE);
1783
Christopher Tate44a27902010-01-27 17:15:49 -08001784 // Kick off the restore, checking for hung agents
1785 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1786 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1787 boolean success = waitUntilOperationComplete(token);
1788
1789 if (!success) {
1790 throw new RuntimeException("restore timeout");
1791 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001792
1793 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001794 //
1795 // !!! TODO: the restored data should be migrated on the server
1796 // side into the current dataset. In that case the new state file
1797 // we just created would reflect the data already extant in the
1798 // backend, so there'd be nothing more to do. Until that happens,
1799 // however, we need to make sure that we record the data to the
1800 // current backend dataset. (Yes, this means shipping the data over
1801 // the wire in both directions. That's bad, but consistency comes
1802 // first, then efficiency.) Once we introduce server-side data
1803 // migration to the newly-restored device's dataset, we will change
1804 // the following from a discard of the newly-written state to the
1805 // "correct" operation of renaming into the canonical state blob.
1806 newStateName.delete(); // TODO: remove; see above comment
1807 //newStateName.renameTo(savedStateName); // TODO: replace with this
1808
Dan Egnorbb9001c2009-07-27 12:20:13 -07001809 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001810 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001811 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001812 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001813 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001814
Christopher Tate96733042009-07-20 14:49:13 -07001815 // If the agent fails restore, it might have put the app's data
1816 // into an incoherent state. For consistency we wipe its data
1817 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001818 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001819 } finally {
1820 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001821 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1822 try { if (newState != null) newState.close(); } catch (IOException e) {}
1823 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001824 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001825 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001826 }
1827 }
1828
Christopher Tate44a27902010-01-27 17:15:49 -08001829 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001830 IBackupTransport mTransport;
1831 PackageInfo mPackage;
1832
Christopher Tate44a27902010-01-27 17:15:49 -08001833 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001834 mTransport = transport;
1835 mPackage = packageInfo;
1836 }
1837
Christopher Tateee0e78a2009-07-02 11:17:03 -07001838 public void run() {
1839 try {
1840 // Clear the on-device backup state to ensure a full backup next time
1841 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1842 File stateFile = new File(stateDir, mPackage.packageName);
1843 stateFile.delete();
1844
1845 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001846 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001847 mTransport.clearBackupData(mPackage);
1848 } catch (RemoteException e) {
1849 // can't happen; the transport is local
1850 } finally {
1851 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001852 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001853 mTransport.finishBackup();
1854 } catch (RemoteException e) {
1855 // can't happen; the transport is local
1856 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001857
1858 // Last but not least, release the cpu
1859 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001860 }
1861 }
1862 }
1863
Christopher Tate44a27902010-01-27 17:15:49 -08001864 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001865 HashSet<String> mQueue;
1866
Christopher Tate44a27902010-01-27 17:15:49 -08001867 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001868 mQueue = transportNames;
1869 }
1870
Christopher Tate4cc86e12009-09-21 19:36:51 -07001871 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001872 try {
1873 for (String transportName : mQueue) {
1874 IBackupTransport transport = getTransport(transportName);
1875 if (transport == null) {
1876 Log.e(TAG, "Requested init for " + transportName + " but not found");
1877 continue;
1878 }
1879
Dan Egnor726247c2009-09-29 19:12:31 -07001880 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001881 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001882 long startRealtime = SystemClock.elapsedRealtime();
1883 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001884
Christopher Tate4cc86e12009-09-21 19:36:51 -07001885 if (status == BackupConstants.TRANSPORT_OK) {
1886 status = transport.finishBackup();
1887 }
1888
1889 // Okay, the wipe really happened. Clean up our local bookkeeping.
1890 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001891 Log.i(TAG, "Device init successful");
1892 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001893 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001894 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001895 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001896 synchronized (mQueueLock) {
1897 recordInitPendingLocked(false, transportName);
1898 }
Dan Egnor726247c2009-09-29 19:12:31 -07001899 } else {
1900 // If this didn't work, requeue this one and try again
1901 // after a suitable interval
1902 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001903 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001904 synchronized (mQueueLock) {
1905 recordInitPendingLocked(true, transportName);
1906 }
1907 // do this via another alarm to make sure of the wakelock states
1908 long delay = transport.requestBackupTime();
1909 if (DEBUG) Log.w(TAG, "init failed on "
1910 + transportName + " resched in " + delay);
1911 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1912 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001913 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001914 }
1915 } catch (RemoteException e) {
1916 // can't happen; the transports are local
1917 } catch (Exception e) {
1918 Log.e(TAG, "Unexpected error performing init", e);
1919 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001920 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001921 mWakelock.release();
1922 }
1923 }
1924 }
1925
Christopher Tatedf01dea2009-06-09 20:45:02 -07001926
Christopher Tate487529a2009-04-29 14:03:25 -07001927 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001928
Dan Egnor852f8e42009-09-30 11:20:45 -07001929 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001930 // Record that we need a backup pass for the caller. Since multiple callers
1931 // may share a uid, we need to note all candidates within that uid and schedule
1932 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001933 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001934
Christopher Tate63d27002009-06-16 17:16:42 -07001935 // If the caller does not hold the BACKUP permission, it can only request a
1936 // backup of its own data.
1937 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001938 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001939 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1940 targets = mBackupParticipants.get(Binder.getCallingUid());
1941 } else {
1942 // a caller with full permission can ask to back up any participating app
1943 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001944 targets = new HashSet<ApplicationInfo>();
1945 int N = mBackupParticipants.size();
1946 for (int i = 0; i < N; i++) {
1947 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1948 if (s != null) {
1949 targets.addAll(s);
1950 }
1951 }
1952 }
Christopher Tate487529a2009-04-29 14:03:25 -07001953 if (targets != null) {
1954 synchronized (mQueueLock) {
1955 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001956 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001957 // validate the caller-supplied package name against the known set of
1958 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001959 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001960 // Add the caller to the set of pending backups. If there is
1961 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001962 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001963 if (mPendingBackups.put(app, req) == null) {
1964 // Journal this request in case of crash. The put()
1965 // operation returned null when this package was not already
1966 // in the set; we want to avoid touching the disk redundantly.
1967 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001968
Christopher Tate22b60d82009-07-07 16:36:02 -07001969 if (DEBUG) {
1970 int numKeys = mPendingBackups.size();
1971 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1972 for (BackupRequest b : mPendingBackups.values()) {
1973 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1974 }
1975 }
1976 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001977 }
1978 }
Christopher Tate487529a2009-04-29 14:03:25 -07001979 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001980 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001981 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1982 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001983 }
1984 }
Christopher Tate46758122009-05-06 11:22:00 -07001985
Christopher Tatecde87f42009-06-12 12:55:53 -07001986 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001987 RandomAccessFile out = null;
1988 try {
1989 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1990 out = new RandomAccessFile(mJournal, "rws");
1991 out.seek(out.length());
1992 out.writeUTF(str);
1993 } catch (IOException e) {
1994 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1995 mJournal = null;
1996 } finally {
1997 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001998 }
1999 }
2000
Christopher Tateee0e78a2009-07-02 11:17:03 -07002001 // Clear the given package's backup data from the current transport
2002 public void clearBackupData(String packageName) {
2003 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
2004 PackageInfo info;
2005 try {
2006 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2007 } catch (NameNotFoundException e) {
2008 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
2009 return;
2010 }
2011
2012 // If the caller does not hold the BACKUP permission, it can only request a
2013 // wipe of its own backed-up data.
2014 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002015 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002016 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2017 apps = mBackupParticipants.get(Binder.getCallingUid());
2018 } else {
2019 // a caller with full permission can ask to back up any participating app
2020 // !!! TODO: allow data-clear of ANY app?
2021 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
2022 apps = new HashSet<ApplicationInfo>();
2023 int N = mBackupParticipants.size();
2024 for (int i = 0; i < N; i++) {
2025 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2026 if (s != null) {
2027 apps.addAll(s);
2028 }
2029 }
2030 }
2031
2032 // now find the given package in the set of candidate apps
2033 for (ApplicationInfo app : apps) {
2034 if (app.packageName.equals(packageName)) {
2035 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
2036 // found it; fire off the clear request
2037 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002038 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002039 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002040 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2041 new ClearParams(getTransport(mCurrentTransport), info));
2042 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002043 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002044 }
2045 break;
2046 }
2047 }
2048 }
2049
Christopher Tateace7f092009-06-15 18:07:25 -07002050 // Run a backup pass immediately for any applications that have declared
2051 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002052 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002054
Christopher Tateace7f092009-06-15 18:07:25 -07002055 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002056 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002057 // Because the alarms we are using can jitter, and we want an *immediate*
2058 // backup pass to happen, we restart the timer beginning with "next time,"
2059 // then manually fire the backup trigger intent ourselves.
2060 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002061 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002062 mRunBackupIntent.send();
2063 } catch (PendingIntent.CanceledException e) {
2064 // should never happen
2065 Log.e(TAG, "run-backup intent cancelled!");
2066 }
Christopher Tate46758122009-05-06 11:22:00 -07002067 }
2068 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002069
Christopher Tate8031a3d2009-07-06 16:36:05 -07002070 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002071 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2073 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002074
Christopher Tate4cc86e12009-09-21 19:36:51 -07002075 Log.i(TAG, "Backup enabled => " + enable);
2076
Christopher Tate6ef58a12009-06-29 14:56:28 -07002077 boolean wasEnabled = mEnabled;
2078 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002079 Settings.Secure.putInt(mContext.getContentResolver(),
2080 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002081 mEnabled = enable;
2082 }
2083
Christopher Tate49401dd2009-07-01 12:34:29 -07002084 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002085 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002086 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002087 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002088 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002089 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002090 if (DEBUG) Log.i(TAG, "Opting out of backup");
2091
Christopher Tateb6787f22009-07-02 17:40:45 -07002092 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002093
2094 // This also constitutes an opt-out, so we wipe any data for
2095 // this device from the backend. We start that process with
2096 // an alarm in order to guarantee wakelock states.
2097 if (wasEnabled && mProvisioned) {
2098 // NOTE: we currently flush every registered transport, not just
2099 // the currently-active one.
2100 HashSet<String> allTransports;
2101 synchronized (mTransports) {
2102 allTransports = new HashSet<String>(mTransports.keySet());
2103 }
2104 // build the set of transports for which we are posting an init
2105 for (String transport : allTransports) {
2106 recordInitPendingLocked(true, transport);
2107 }
2108 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2109 mRunInitIntent);
2110 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002111 }
2112 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002113 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002114
Christopher Tatecce9da52010-02-03 15:11:15 -08002115 // Enable/disable automatic restore of app data at install time
2116 public void setAutoRestore(boolean doAutoRestore) {
2117 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2118 "setBackupEnabled");
2119
2120 Log.i(TAG, "Auto restore => " + doAutoRestore);
2121
2122 synchronized (this) {
2123 Settings.Secure.putInt(mContext.getContentResolver(),
2124 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2125 mAutoRestore = doAutoRestore;
2126 }
2127 }
2128
Christopher Tate8031a3d2009-07-06 16:36:05 -07002129 // Mark the backup service as having been provisioned
2130 public void setBackupProvisioned(boolean available) {
2131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2132 "setBackupProvisioned");
2133
2134 boolean wasProvisioned = mProvisioned;
2135 synchronized (this) {
2136 Settings.Secure.putInt(mContext.getContentResolver(),
2137 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2138 mProvisioned = available;
2139 }
2140
2141 synchronized (mQueueLock) {
2142 if (available && !wasProvisioned && mEnabled) {
2143 // we're now good to go, so start the backup alarms
2144 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2145 } else if (!available) {
2146 // No longer enabled, so stop running backups
2147 Log.w(TAG, "Backup service no longer provisioned");
2148 mAlarmManager.cancel(mRunBackupIntent);
2149 }
2150 }
2151 }
2152
2153 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002154 // We used to use setInexactRepeating(), but that may be linked to
2155 // backups running at :00 more often than not, creating load spikes.
2156 // Schedule at an exact time for now, and also add a bit of "fuzz".
2157
2158 Random random = new Random();
2159 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2160 random.nextInt(FUZZ_MILLIS);
2161 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2162 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002163 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002164 }
2165
Christopher Tate6ef58a12009-06-29 14:56:28 -07002166 // Report whether the backup mechanism is currently enabled
2167 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002168 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002169 return mEnabled; // no need to synchronize just to read it
2170 }
2171
Christopher Tate91717492009-06-26 21:07:13 -07002172 // Report the name of the currently active transport
2173 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002174 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002175 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002176 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002177 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002178 }
2179
Christopher Tate91717492009-06-26 21:07:13 -07002180 // Report all known, available backup transports
2181 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002182 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002183
Christopher Tate91717492009-06-26 21:07:13 -07002184 String[] list = null;
2185 ArrayList<String> known = new ArrayList<String>();
2186 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2187 if (entry.getValue() != null) {
2188 known.add(entry.getKey());
2189 }
2190 }
2191
2192 if (known.size() > 0) {
2193 list = new String[known.size()];
2194 known.toArray(list);
2195 }
2196 return list;
2197 }
2198
2199 // Select which transport to use for the next backup operation. If the given
2200 // name is not one of the available transports, no action is taken and the method
2201 // returns null.
2202 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002204
2205 synchronized (mTransports) {
2206 String prevTransport = null;
2207 if (mTransports.get(transport) != null) {
2208 prevTransport = mCurrentTransport;
2209 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002210 Settings.Secure.putString(mContext.getContentResolver(),
2211 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002212 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2213 + " returning " + prevTransport);
2214 } else {
2215 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2216 }
2217 return prevTransport;
2218 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002219 }
2220
2221 // Callback: a requested backup agent has been instantiated. This should only
2222 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002223 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002224 synchronized(mAgentConnectLock) {
2225 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2226 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2227 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2228 mConnectedAgent = agent;
2229 mConnecting = false;
2230 } else {
2231 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2232 + " claiming agent connected");
2233 }
2234 mAgentConnectLock.notifyAll();
2235 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002236 }
2237
2238 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2239 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002240 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002241 public void agentDisconnected(String packageName) {
2242 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002243 synchronized(mAgentConnectLock) {
2244 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2245 mConnectedAgent = null;
2246 mConnecting = false;
2247 } else {
2248 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2249 + " claiming agent disconnected");
2250 }
2251 mAgentConnectLock.notifyAll();
2252 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002253 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002254
Christopher Tate8c850b72009-06-07 19:33:20 -07002255 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002256 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002258
2259 synchronized(this) {
2260 if (mActiveRestoreSession != null) {
2261 Log.d(TAG, "Restore session requested but one already active");
2262 return null;
2263 }
Christopher Tate80202c82010-01-25 19:37:47 -08002264 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002265 }
2266 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002267 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002268
Christopher Tate44a27902010-01-27 17:15:49 -08002269 // Note that a currently-active backup agent has notified us that it has
2270 // completed the given outstanding asynchronous backup/restore operation.
2271 public void opComplete(int token) {
2272 synchronized (mCurrentOpLock) {
2273 if (DEBUG) Log.v(TAG, "opComplete: " + token);
2274 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2275 mCurrentOpLock.notifyAll();
2276 }
2277 }
2278
Christopher Tate9b3905c2009-06-08 15:24:01 -07002279 // ----- Restore session -----
2280
Christopher Tate80202c82010-01-25 19:37:47 -08002281 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002282 private static final String TAG = "RestoreSession";
2283
Christopher Tate9b3905c2009-06-08 15:24:01 -07002284 private IBackupTransport mRestoreTransport = null;
2285 RestoreSet[] mRestoreSets = null;
2286
Christopher Tate80202c82010-01-25 19:37:47 -08002287 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002288 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002289 }
2290
2291 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002292 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002294 "getAvailableRestoreSets");
2295
Christopher Tatef68eb502009-06-16 11:02:01 -07002296 try {
Christopher Tate43383042009-07-13 15:17:13 -07002297 if (mRestoreTransport == null) {
2298 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002299 return null;
2300 }
2301 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002302 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002303 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002304 }
2305 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002306 } catch (Exception e) {
2307 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2308 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002309 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002310 }
2311
Christopher Tate84725812010-02-04 15:52:40 -08002312 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002313 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2314 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002315
Christopher Tatef2c321a2009-08-10 15:43:36 -07002316 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2317 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002318
Dan Egnor0084da52009-07-29 12:57:16 -07002319 if (mRestoreTransport == null || mRestoreSets == null) {
2320 Log.e(TAG, "Ignoring performRestore() with no restore set");
2321 return -1;
2322 }
2323
Christopher Tate21ab6a52009-09-24 18:01:46 -07002324 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002325 for (int i = 0; i < mRestoreSets.length; i++) {
2326 if (token == mRestoreSets[i].token) {
2327 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002328 mWakelock.acquire();
2329 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2330 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2331 mBackupHandler.sendMessage(msg);
2332 Binder.restoreCallingIdentity(oldId);
2333 return 0;
2334 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002335 }
2336 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002337
2338 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002339 return -1;
2340 }
2341
Christopher Tate84725812010-02-04 15:52:40 -08002342 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
2343 if (DEBUG) Log.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
2344
2345 PackageInfo app = null;
2346 try {
2347 app = mPackageManager.getPackageInfo(packageName, 0);
2348 } catch (NameNotFoundException nnf) {
2349 Log.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2350 return -1;
2351 }
2352
2353 // If the caller is not privileged and is not coming from the target
2354 // app's uid, throw a permission exception back to the caller.
2355 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2356 Binder.getCallingPid(), Binder.getCallingUid());
2357 if ((perm == PackageManager.PERMISSION_DENIED) &&
2358 (app.applicationInfo.uid != Binder.getCallingUid())) {
2359 Log.w(TAG, "restorePackage: bad packageName=" + packageName
2360 + " or calling uid=" + Binder.getCallingUid());
2361 throw new SecurityException("No permission to restore other packages");
2362 }
2363
2364 // So far so good; we're allowed to try to restore this package. Now
2365 // check whether there is data for it in the current dataset, falling back
2366 // to the ancestral dataset if not.
2367 long token = mAncestralToken;
2368 synchronized (mQueueLock) {
2369 if (mEverStoredApps.contains(packageName)) {
2370 token = mCurrentToken;
2371 }
2372 }
2373
2374 // If we didn't come up with a place to look -- no ancestral dataset and
2375 // the app has never been backed up from this device -- there's nothing
2376 // to do but return failure.
2377 if (token == 0) {
2378 return -1;
2379 }
2380
2381 // Ready to go: enqueue the restore request and claim success
2382 long oldId = Binder.clearCallingIdentity();
2383 mWakelock.acquire();
2384 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2385 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app);
2386 mBackupHandler.sendMessage(msg);
2387 Binder.restoreCallingIdentity(oldId);
2388 return 0;
2389 }
2390
Dan Egnor0084da52009-07-29 12:57:16 -07002391 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002392 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002393 "endRestoreSession");
2394
Dan Egnor0084da52009-07-29 12:57:16 -07002395 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002396
Dan Egnor0084da52009-07-29 12:57:16 -07002397 synchronized (this) {
2398 try {
2399 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2400 } catch (Exception e) {
2401 Log.e(TAG, "Error in finishRestore", e);
2402 } finally {
2403 mRestoreTransport = null;
2404 }
2405 }
2406
2407 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002408 if (BackupManagerService.this.mActiveRestoreSession == this) {
2409 BackupManagerService.this.mActiveRestoreSession = null;
2410 } else {
2411 Log.e(TAG, "ending non-current restore session");
2412 }
2413 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002414 }
2415 }
2416
Christopher Tate043dadc2009-06-02 16:11:00 -07002417
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002418 @Override
2419 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2420 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002421 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002422 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002423 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tate55f931a2009-09-29 17:17:34 -07002424 pw.println("Last backup pass: " + mLastBackupPass
2425 + " (now = " + System.currentTimeMillis() + ')');
2426 pw.println(" next scheduled: " + mNextBackupPass);
2427
Christopher Tate91717492009-06-26 21:07:13 -07002428 pw.println("Available transports:");
2429 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002430 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2431 try {
2432 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2433 for (File f : dir.listFiles()) {
2434 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2435 }
2436 } catch (RemoteException e) {
2437 Log.e(TAG, "Error in transportDirName()", e);
2438 pw.println(" Error: " + e);
2439 }
Christopher Tate91717492009-06-26 21:07:13 -07002440 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002441
2442 pw.println("Pending init: " + mPendingInits.size());
2443 for (String s : mPendingInits) {
2444 pw.println(" " + s);
2445 }
2446
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002447 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002448 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002449 for (int i=0; i<N; i++) {
2450 int uid = mBackupParticipants.keyAt(i);
2451 pw.print(" uid: ");
2452 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002453 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2454 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002455 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002456 }
2457 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002458
Christopher Tateb49ceb32010-02-08 16:22:24 -08002459 pw.println("Ancestral packages: "
2460 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
2461 for (String pkg : mAncestralPackages) {
2462 pw.println(" " + pkg);
2463 }
2464
Christopher Tate73e02522009-07-15 14:18:26 -07002465 pw.println("Ever backed up: " + mEverStoredApps.size());
2466 for (String pkg : mEverStoredApps) {
2467 pw.println(" " + pkg);
2468 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002469
2470 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002471 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002472 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002473 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002474 }
2475 }
Christopher Tate487529a2009-04-29 14:03:25 -07002476}