blob: 601fa21483e4d7c8d97aa893b3b370e28f8e5a16 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.RestoreSet;
27import android.app.backup.IBackupManager;
28import android.app.backup.IRestoreObserver;
29import android.app.backup.IRestoreSession;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070031import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.content.Context;
33import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070036import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070037import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080038import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070039import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070041import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080042import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070045import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080050import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070052import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070053import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070057import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070059import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080062import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070063
Christopher Tated55e18a2009-09-21 10:12:59 -070064import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070065import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070067import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070068
Christopher Tatecde87f42009-06-12 12:55:53 -070069import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070070import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080072import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070073import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070074import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070075import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040077import java.util.ArrayList;
78import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070079import java.util.HashSet;
80import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070081import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070082import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080083import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070084
85class BackupManagerService extends IBackupManager.Stub {
86 private static final String TAG = "BackupManagerService";
Chris Tatea9c50432010-10-11 14:37:12 -070087 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070088
Christopher Tate49401dd2009-07-01 12:34:29 -070089 // How often we perform a backup pass. Privileged external callers can
90 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070091 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070092
Dan Egnorc1c49c02009-10-30 17:35:39 -070093 // Random variation in backup scheduling time to avoid server load spikes
94 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
95
Christopher Tate8031a3d2009-07-06 16:36:05 -070096 // The amount of time between the initial provisioning of the device and
97 // the first backup pass.
98 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
99
Christopher Tate45281862010-03-05 15:46:30 -0800100 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
101 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
102 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700103 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700104 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700105 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700106 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700107 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700108 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
109 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800110 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700111
112 // Timeout interval for deciding that a bind or clear-data has taken too long
113 static final long TIMEOUT_INTERVAL = 10 * 1000;
114
Christopher Tate44a27902010-01-27 17:15:49 -0800115 // Timeout intervals for agent backup & restore operations
116 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
117 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
118
Christopher Tate487529a2009-04-29 14:03:25 -0700119 private Context mContext;
120 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800121 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700122 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700123 private PowerManager mPowerManager;
124 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800125 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700126
Christopher Tate73e02522009-07-15 14:18:26 -0700127 boolean mEnabled; // access to this is synchronized on 'this'
128 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800129 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700130 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800131 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
132 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700133 PendingIntent mRunBackupIntent, mRunInitIntent;
134 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700135 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700136 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700137 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700138 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700139 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700140 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700141 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700142
Christopher Tate181fafa2009-05-14 11:12:14 -0700143 BackupRequest(ApplicationInfo app, boolean isFull) {
144 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700145 fullBackup = isFull;
146 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700147
148 public String toString() {
149 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
150 }
Christopher Tate46758122009-05-06 11:22:00 -0700151 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400152 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700153 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700154 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700155
156 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700157 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700158
159 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700160 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700161
Christopher Tate043dadc2009-06-02 16:11:00 -0700162 // The thread performing the sequence of queued backups binds to each app's agent
163 // in succession. Bind notifications are asynchronously delivered through the
164 // Activity Manager; use this lock object to signal when a requested binding has
165 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700166 final Object mAgentConnectLock = new Object();
167 IBackupAgent mConnectedAgent;
168 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700169 volatile long mLastBackupPass;
170 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700171
Christopher Tate55f931a2009-09-29 17:17:34 -0700172 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700173 final Object mClearDataLock = new Object();
174 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700175
Christopher Tate91717492009-06-26 21:07:13 -0700176 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700177 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700178 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700179 String mCurrentTransport;
180 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800181 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700182
Christopher Tate2d449afe2010-03-29 19:14:24 -0700183 class RestoreGetSetsParams {
184 public IBackupTransport transport;
185 public ActiveRestoreSession session;
186 public IRestoreObserver observer;
187
188 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
189 IRestoreObserver _observer) {
190 transport = _transport;
191 session = _session;
192 observer = _observer;
193 }
194 }
195
Christopher Tate73e02522009-07-15 14:18:26 -0700196 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700197 public IBackupTransport transport;
198 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700199 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800200 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800201 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700202 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800203
204 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700205 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800206 transport = _transport;
207 observer = _obs;
208 token = _token;
209 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800210 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700211 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800212 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700213
Chris Tate249345b2010-10-29 12:57:04 -0700214 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
215 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700216 transport = _transport;
217 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700218 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800219 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800220 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700221 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700222 }
223 }
224
Christopher Tate73e02522009-07-15 14:18:26 -0700225 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700226 public IBackupTransport transport;
227 public PackageInfo packageInfo;
228
229 ClearParams(IBackupTransport _transport, PackageInfo _info) {
230 transport = _transport;
231 packageInfo = _info;
232 }
233 }
234
Christopher Tate44a27902010-01-27 17:15:49 -0800235 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
236 // token is the index of the entry in the pending-operations list.
237 static final int OP_PENDING = 0;
238 static final int OP_ACKNOWLEDGED = 1;
239 static final int OP_TIMEOUT = -1;
240
241 final SparseIntArray mCurrentOperations = new SparseIntArray();
242 final Object mCurrentOpLock = new Object();
243 final Random mTokenGenerator = new Random();
244
Christopher Tate5cb400b2009-06-25 16:03:14 -0700245 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700246 File mBaseStateDir;
247 File mDataDir;
248 File mJournalDir;
249 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700250
Christopher Tate84725812010-02-04 15:52:40 -0800251 // Keep a log of all the apps we've ever backed up, and what the
252 // dataset tokens are for both the current backup dataset and
253 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700254 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700255 HashSet<String> mEverStoredApps = new HashSet<String>();
256
Christopher Tateb49ceb32010-02-08 16:22:24 -0800257 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800258 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800259 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800260 long mAncestralToken = 0;
261 long mCurrentToken = 0;
262
Christopher Tate4cc86e12009-09-21 19:36:51 -0700263 // Persistently track the need to do a full init
264 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
265 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700266
Christopher Tate44a27902010-01-27 17:15:49 -0800267 // ----- Asynchronous backup/restore handler thread -----
268
269 private class BackupHandler extends Handler {
270 public BackupHandler(Looper looper) {
271 super(looper);
272 }
273
274 public void handleMessage(Message msg) {
275
276 switch (msg.what) {
277 case MSG_RUN_BACKUP:
278 {
279 mLastBackupPass = System.currentTimeMillis();
280 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
281
282 IBackupTransport transport = getTransport(mCurrentTransport);
283 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800284 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800285 mWakelock.release();
286 break;
287 }
288
289 // snapshot the pending-backup set and work on that
290 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800291 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800292 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800293 // Do we have any work to do? Construct the work queue
294 // then release the synchronization lock to actually run
295 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800296 if (mPendingBackups.size() > 0) {
297 for (BackupRequest b: mPendingBackups.values()) {
298 queue.add(b);
299 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800300 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800301 mPendingBackups.clear();
302
303 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800304 mJournal = null;
305
Christopher Tate44a27902010-01-27 17:15:49 -0800306 }
307 }
Christopher Tatec61da312010-02-05 10:41:27 -0800308
309 if (queue.size() > 0) {
310 // At this point, we have started a new journal file, and the old
311 // file identity is being passed to the backup processing thread.
312 // When it completes successfully, that old journal file will be
313 // deleted. If we crash prior to that, the old journal is parsed
314 // at next boot and the journaled requests fulfilled.
315 (new PerformBackupTask(transport, queue, oldJournal)).run();
316 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800317 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800318 mWakelock.release();
319 }
Christopher Tate44a27902010-01-27 17:15:49 -0800320 break;
321 }
322
323 case MSG_RUN_FULL_BACKUP:
324 break;
325
326 case MSG_RUN_RESTORE:
327 {
328 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800329 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800330 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700331 params.token, params.pkgInfo, params.pmToken,
332 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800333 break;
334 }
335
336 case MSG_RUN_CLEAR:
337 {
338 ClearParams params = (ClearParams)msg.obj;
339 (new PerformClearTask(params.transport, params.packageInfo)).run();
340 break;
341 }
342
343 case MSG_RUN_INITIALIZE:
344 {
345 HashSet<String> queue;
346
347 // Snapshot the pending-init queue and work on that
348 synchronized (mQueueLock) {
349 queue = new HashSet<String>(mPendingInits);
350 mPendingInits.clear();
351 }
352
353 (new PerformInitializeTask(queue)).run();
354 break;
355 }
356
Christopher Tate2d449afe2010-03-29 19:14:24 -0700357 case MSG_RUN_GET_RESTORE_SETS:
358 {
359 // Like other async operations, this is entered with the wakelock held
360 RestoreSet[] sets = null;
361 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
362 try {
363 sets = params.transport.getAvailableRestoreSets();
364 // cache the result in the active session
365 synchronized (params.session) {
366 params.session.mRestoreSets = sets;
367 }
368 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
369 } catch (Exception e) {
370 Slog.e(TAG, "Error from transport getting set list");
371 } finally {
372 if (params.observer != null) {
373 try {
374 params.observer.restoreSetsAvailable(sets);
375 } catch (RemoteException re) {
376 Slog.e(TAG, "Unable to report listing to observer");
377 } catch (Exception e) {
378 Slog.e(TAG, "Restore observer threw", e);
379 }
380 }
381
382 mWakelock.release();
383 }
384 break;
385 }
386
Christopher Tate44a27902010-01-27 17:15:49 -0800387 case MSG_TIMEOUT:
388 {
389 synchronized (mCurrentOpLock) {
390 final int token = msg.arg1;
391 int state = mCurrentOperations.get(token, OP_TIMEOUT);
392 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800393 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800394 mCurrentOperations.put(token, OP_TIMEOUT);
395 }
396 mCurrentOpLock.notifyAll();
397 }
398 break;
399 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800400
401 case MSG_RESTORE_TIMEOUT:
402 {
403 synchronized (BackupManagerService.this) {
404 if (mActiveRestoreSession != null) {
405 // Client app left the restore session dangling. We know that it
406 // can't be in the middle of an actual restore operation because
407 // those are executed serially on this same handler thread. Clean
408 // up now.
409 Slog.w(TAG, "Restore session timed out; aborting");
410 post(mActiveRestoreSession.new EndRestoreRunnable(
411 BackupManagerService.this, mActiveRestoreSession));
412 }
413 }
414 }
Christopher Tate44a27902010-01-27 17:15:49 -0800415 }
416 }
417 }
418
419 // ----- Main service implementation -----
420
Christopher Tate487529a2009-04-29 14:03:25 -0700421 public BackupManagerService(Context context) {
422 mContext = context;
423 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700424 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700425 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700426
Christopher Tateb6787f22009-07-02 17:40:45 -0700427 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
428 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
429
Christopher Tate44a27902010-01-27 17:15:49 -0800430 mBackupManagerBinder = asInterface(asBinder());
431
432 // spin up the backup/restore handler thread
433 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
434 mHandlerThread.start();
435 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
436
Christopher Tate22b87872009-05-04 16:41:53 -0700437 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700438 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700439 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700440 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700441 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800442 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800443 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800444 // If Encrypted file systems is enabled or disabled, this call will return the
445 // correct directory.
446 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
447 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700448 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700449
Christopher Tate4cc86e12009-09-21 19:36:51 -0700450 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700451 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700452 IntentFilter filter = new IntentFilter();
453 filter.addAction(RUN_BACKUP_ACTION);
454 context.registerReceiver(mRunBackupReceiver, filter,
455 android.Manifest.permission.BACKUP, null);
456
457 mRunInitReceiver = new RunInitializeReceiver();
458 filter = new IntentFilter();
459 filter.addAction(RUN_INITIALIZE_ACTION);
460 context.registerReceiver(mRunInitReceiver, filter,
461 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700462
463 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700464 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
465 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
466
Christopher Tate4cc86e12009-09-21 19:36:51 -0700467 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
468 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
469 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
470
Christopher Tatecde87f42009-06-12 12:55:53 -0700471 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700472 mJournalDir = new File(mBaseStateDir, "pending");
473 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700474 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700475
Christopher Tate73e02522009-07-15 14:18:26 -0700476 // Set up the various sorts of package tracking we do
477 initPackageTracking();
478
Christopher Tateabce4e82009-06-18 18:35:32 -0700479 // Build our mapping of uid to backup client services. This implicitly
480 // schedules a backup pass on the Package Manager metadata the first
481 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700482 synchronized (mBackupParticipants) {
483 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700484 }
485
Dan Egnor87a02bc2009-06-17 02:30:10 -0700486 // Set up our transport options and initialize the default transport
487 // TODO: Have transports register themselves somehow?
488 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700489 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700490 ComponentName localName = new ComponentName(context, LocalTransport.class);
491 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700492
Christopher Tate91717492009-06-26 21:07:13 -0700493 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700494 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
495 Settings.Secure.BACKUP_TRANSPORT);
496 if ("".equals(mCurrentTransport)) {
497 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700498 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800499 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700500
501 // Attach to the Google backup transport. When this comes up, it will set
502 // itself as the current transport because we explicitly reset mCurrentTransport
503 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700504 ComponentName transportComponent = new ComponentName("com.google.android.backup",
505 "com.google.android.backup.BackupTransportService");
506 try {
507 // If there's something out there that is supposed to be the Google
508 // backup transport, make sure it's legitimately part of the OS build
509 // and not an app lying about its package name.
510 ApplicationInfo info = mPackageManager.getApplicationInfo(
511 transportComponent.getPackageName(), 0);
512 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
513 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
514 Intent intent = new Intent().setComponent(transportComponent);
515 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
516 } else {
517 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
518 }
519 } catch (PackageManager.NameNotFoundException nnf) {
520 // No such package? No binding.
521 if (DEBUG) Slog.v(TAG, "Google transport not present");
522 }
Christopher Tateaa088442009-06-16 18:25:46 -0700523
Christopher Tatecde87f42009-06-12 12:55:53 -0700524 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700525 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700526 parseLeftoverJournals();
527
Christopher Tateb6787f22009-07-02 17:40:45 -0700528 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700529 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700530
531 // Start the backup passes going
532 setBackupEnabled(areEnabled);
533 }
534
535 private class RunBackupReceiver extends BroadcastReceiver {
536 public void onReceive(Context context, Intent intent) {
537 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700538 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700539 if (mPendingInits.size() > 0) {
540 // If there are pending init operations, we process those
541 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800542 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700543 try {
544 mAlarmManager.cancel(mRunInitIntent);
545 mRunInitIntent.send();
546 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800547 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700548 // can't really do more than bail here
549 }
550 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800551 // Don't run backups now if we're disabled or not yet
552 // fully set up.
553 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800554 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700555
556 // Acquire the wakelock and pass it to the backup thread. it will
557 // be released once backup concludes.
558 mWakelock.acquire();
559
560 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
561 mBackupHandler.sendMessage(msg);
562 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800563 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700564 }
565 }
566 }
567 }
568 }
569 }
570
571 private class RunInitializeReceiver extends BroadcastReceiver {
572 public void onReceive(Context context, Intent intent) {
573 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
574 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800575 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700576
577 // Acquire the wakelock and pass it to the init thread. it will
578 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700579 mWakelock.acquire();
580
Christopher Tate4cc86e12009-09-21 19:36:51 -0700581 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700582 mBackupHandler.sendMessage(msg);
583 }
584 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700585 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700586 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700587
Christopher Tate73e02522009-07-15 14:18:26 -0700588 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800589 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700590
Christopher Tate84725812010-02-04 15:52:40 -0800591 // Remember our ancestral dataset
592 mTokenFile = new File(mBaseStateDir, "ancestral");
593 try {
594 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800595 int version = tf.readInt();
596 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
597 mAncestralToken = tf.readLong();
598 mCurrentToken = tf.readLong();
599
600 int numPackages = tf.readInt();
601 if (numPackages >= 0) {
602 mAncestralPackages = new HashSet<String>();
603 for (int i = 0; i < numPackages; i++) {
604 String pkgName = tf.readUTF();
605 mAncestralPackages.add(pkgName);
606 }
607 }
608 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800609 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800610 } catch (FileNotFoundException fnf) {
611 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800612 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800613 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800614 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800615 }
616
Christopher Tatee97e8072009-07-15 16:45:50 -0700617 // Keep a log of what apps we've ever backed up. Because we might have
618 // rebooted in the middle of an operation that was removing something from
619 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700620 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700621 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700622
Christopher Tatee97e8072009-07-15 16:45:50 -0700623 // If we were in the middle of removing something from the ever-backed-up
624 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700625 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700626 if (tempProcessedFile.exists()) {
627 tempProcessedFile.delete();
628 }
629
Dan Egnor852f8e42009-09-30 11:20:45 -0700630 // If there are previous contents, parse them out then start a new
631 // file to continue the recordkeeping.
632 if (mEverStored.exists()) {
633 RandomAccessFile temp = null;
634 RandomAccessFile in = null;
635
636 try {
637 temp = new RandomAccessFile(tempProcessedFile, "rws");
638 in = new RandomAccessFile(mEverStored, "r");
639
640 while (true) {
641 PackageInfo info;
642 String pkg = in.readUTF();
643 try {
644 info = mPackageManager.getPackageInfo(pkg, 0);
645 mEverStoredApps.add(pkg);
646 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800647 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700648 } catch (NameNotFoundException e) {
649 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800650 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700651 }
652 }
653 } catch (EOFException e) {
654 // Once we've rewritten the backup history log, atomically replace the
655 // old one with the new one then reopen the file for continuing use.
656 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800657 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700658 }
659 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800660 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700661 } finally {
662 try { if (temp != null) temp.close(); } catch (IOException e) {}
663 try { if (in != null) in.close(); } catch (IOException e) {}
664 }
665 }
666
Christopher Tate73e02522009-07-15 14:18:26 -0700667 // Register for broadcasts about package install, etc., so we can
668 // update the provider list.
669 IntentFilter filter = new IntentFilter();
670 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
671 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
672 filter.addDataScheme("package");
673 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800674 // Register for events related to sdcard installation.
675 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800676 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
677 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800678 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700679 }
680
Christopher Tatecde87f42009-06-12 12:55:53 -0700681 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700682 for (File f : mJournalDir.listFiles()) {
683 if (mJournal == null || f.compareTo(mJournal) != 0) {
684 // This isn't the current journal, so it must be a leftover. Read
685 // out the package names mentioned there and schedule them for
686 // backup.
687 RandomAccessFile in = null;
688 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400689 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700690 in = new RandomAccessFile(f, "r");
691 while (true) {
692 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400693 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700694 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700695 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700696 } catch (EOFException e) {
697 // no more data; we're done
698 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800699 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700700 } finally {
701 // close/delete the file
702 try { if (in != null) in.close(); } catch (IOException e) {}
703 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700704 }
705 }
706 }
707 }
708
Christopher Tate4cc86e12009-09-21 19:36:51 -0700709 // Maintain persistent state around whether need to do an initialize operation.
710 // Must be called with the queue lock held.
711 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800712 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700713 + " on transport " + transportName);
714 try {
715 IBackupTransport transport = getTransport(transportName);
716 String transportDirName = transport.transportDirName();
717 File stateDir = new File(mBaseStateDir, transportDirName);
718 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
719
720 if (isPending) {
721 // We need an init before we can proceed with sending backup data.
722 // Record that with an entry in our set of pending inits, as well as
723 // journaling it via creation of a sentinel file.
724 mPendingInits.add(transportName);
725 try {
726 (new FileOutputStream(initPendingFile)).close();
727 } catch (IOException ioe) {
728 // Something is badly wrong with our permissions; just try to move on
729 }
730 } else {
731 // No more initialization needed; wipe the journal and reset our state.
732 initPendingFile.delete();
733 mPendingInits.remove(transportName);
734 }
735 } catch (RemoteException e) {
736 // can't happen; the transport is local
737 }
738 }
739
Christopher Tated55e18a2009-09-21 10:12:59 -0700740 // Reset all of our bookkeeping, in response to having been told that
741 // the backend data has been wiped [due to idle expiry, for example],
742 // so we must re-upload all saved settings.
743 void resetBackupState(File stateFileDir) {
744 synchronized (mQueueLock) {
745 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700746 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700747 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700748
Christopher Tate84725812010-02-04 15:52:40 -0800749 mCurrentToken = 0;
750 writeRestoreTokens();
751
Christopher Tated55e18a2009-09-21 10:12:59 -0700752 // Remove all the state files
753 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700754 // ... but don't touch the needs-init sentinel
755 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
756 sf.delete();
757 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700758 }
759
760 // Enqueue a new backup of every participant
761 int N = mBackupParticipants.size();
762 for (int i=0; i<N; i++) {
763 int uid = mBackupParticipants.keyAt(i);
764 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
765 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700766 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700767 }
768 }
769 }
770 }
771
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800772 // Add a transport to our set of available backends. If 'transport' is null, this
773 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700774 private void registerTransport(String name, IBackupTransport transport) {
775 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800776 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800777 if (transport != null) {
778 mTransports.put(name, transport);
779 } else {
780 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800781 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800782 mCurrentTransport = null;
783 }
784 // Nothing further to do in the unregistration case
785 return;
786 }
Christopher Tate91717492009-06-26 21:07:13 -0700787 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700788
789 // If the init sentinel file exists, we need to be sure to perform the init
790 // as soon as practical. We also create the state directory at registration
791 // time to ensure it's present from the outset.
792 try {
793 String transportName = transport.transportDirName();
794 File stateDir = new File(mBaseStateDir, transportName);
795 stateDir.mkdirs();
796
797 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
798 if (initSentinel.exists()) {
799 synchronized (mQueueLock) {
800 mPendingInits.add(transportName);
801
802 // TODO: pick a better starting time than now + 1 minute
803 long delay = 1000 * 60; // one minute, in milliseconds
804 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
805 System.currentTimeMillis() + delay, mRunInitIntent);
806 }
807 }
808 } catch (RemoteException e) {
809 // can't happen, the transport is local
810 }
Christopher Tate91717492009-06-26 21:07:13 -0700811 }
812
Christopher Tate3799bc22009-05-06 16:13:56 -0700813 // ----- Track installation/removal of packages -----
814 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
815 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700817
Christopher Tate3799bc22009-05-06 16:13:56 -0700818 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800819 boolean replacing = false;
820 boolean added = false;
821 Bundle extras = intent.getExtras();
822 String pkgList[] = null;
823 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
824 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
825 Uri uri = intent.getData();
826 if (uri == null) {
827 return;
828 }
829 String pkgName = uri.getSchemeSpecificPart();
830 if (pkgName != null) {
831 pkgList = new String[] { pkgName };
832 }
833 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
834 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800835 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800836 added = true;
837 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800838 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800839 added = false;
840 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
841 }
842 if (pkgList == null || pkgList.length == 0) {
843 return;
844 }
845 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700846 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800847 for (String pkgName : pkgList) {
848 if (replacing) {
849 // The package was just upgraded
850 updatePackageParticipantsLocked(pkgName);
851 } else {
852 // The package was just added
853 addPackageParticipantsLocked(pkgName);
854 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 }
856 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800857 } else {
858 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700859 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
860 } else {
861 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800862 for (String pkgName : pkgList) {
863 removePackageParticipantsLocked(pkgName);
864 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700865 }
866 }
867 }
868 }
869 };
870
Dan Egnor87a02bc2009-06-17 02:30:10 -0700871 // ----- Track connection to GoogleBackupTransport service -----
872 ServiceConnection mGoogleConnection = new ServiceConnection() {
873 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800874 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700875 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700876 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700877 }
878
879 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800880 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700881 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700882 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700883 }
884 };
885
Christopher Tate181fafa2009-05-14 11:12:14 -0700886 // Add the backup agents in the given package to our set of known backup participants.
887 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700888 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700889 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800890 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700891 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700892 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700893 }
894
Christopher Tate181fafa2009-05-14 11:12:14 -0700895 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700896 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700897 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800898 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700899 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800900 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700901 + " uid=" + p.applicationInfo.uid
902 + " killAfterRestore="
903 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700904 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700905 }
906 }
907
Dan Egnorefe52642009-06-24 00:16:33 -0700908 for (PackageInfo pkg : targetPkgs) {
909 if (packageName == null || pkg.packageName.equals(packageName)) {
910 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700911 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700912 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700913 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700914 mBackupParticipants.put(uid, set);
915 }
Dan Egnorefe52642009-06-24 00:16:33 -0700916 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700917
918 // If we've never seen this app before, schedule a backup for it
919 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800920 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700921 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700922 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700923 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700924 }
Christopher Tate487529a2009-04-29 14:03:25 -0700925 }
926 }
927
Christopher Tate6785dd82009-06-18 15:58:25 -0700928 // Remove the given package's entry from our known active set. If
929 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700930 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800931 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700932 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700933 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700934 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700935 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700936 int flags = PackageManager.GET_SIGNATURES;
937 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700938 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700939 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700940 }
941 } else {
942 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700943 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700944 }
945 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700946 }
947
Joe Onorato8ad02812009-05-13 01:41:44 -0400948 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700949 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700950 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800951 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700952 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700953 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800954 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700955 }
956 }
Dan Egnorefe52642009-06-24 00:16:33 -0700957 for (PackageInfo pkg : agents) {
958 if (packageName == null || pkg.packageName.equals(packageName)) {
959 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700960 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700961 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700962 // Find the existing entry with the same package name, and remove it.
963 // We can't just remove(app) because the instances are different.
964 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700965 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700966 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700967 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700968 break;
969 }
970 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700971 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700972 mBackupParticipants.delete(uid);
973 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700974 }
975 }
976 }
977 }
978
Christopher Tate181fafa2009-05-14 11:12:14 -0700979 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700980 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700981 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700982 int flags = PackageManager.GET_SIGNATURES;
983 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
984 int N = packages.size();
985 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700986 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700987 try {
988 ApplicationInfo app = pkg.applicationInfo;
989 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800990 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700991 packages.remove(a);
992 }
993 else {
994 // we will need the shared library path, so look that up and store it here
995 app = mPackageManager.getApplicationInfo(pkg.packageName,
996 PackageManager.GET_SHARED_LIBRARY_FILES);
997 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
998 }
999 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001000 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001001 }
1002 }
Dan Egnorefe52642009-06-24 00:16:33 -07001003 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001004 }
Christopher Tateaa088442009-06-16 18:25:46 -07001005
Christopher Tate3799bc22009-05-06 16:13:56 -07001006 // Reset the given package's known backup participants. Unlike add/remove, the update
1007 // action cannot be passed a null package name.
1008 void updatePackageParticipantsLocked(String packageName) {
1009 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001010 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001011 return;
1012 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001013 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001014
1015 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001016 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001017 removePackageParticipantsLockedInner(packageName, allApps);
1018 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001019 }
1020
Christopher Tate84725812010-02-04 15:52:40 -08001021 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001022 // backed up at least once
1023 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001024 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1025
1026 synchronized (mEverStoredApps) {
1027 if (!mEverStoredApps.add(packageName)) return;
1028
1029 RandomAccessFile out = null;
1030 try {
1031 out = new RandomAccessFile(mEverStored, "rws");
1032 out.seek(out.length());
1033 out.writeUTF(packageName);
1034 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001035 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001036 } finally {
1037 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001038 }
1039 }
1040 }
1041
Christopher Tatee97e8072009-07-15 16:45:50 -07001042 // Remove our awareness of having ever backed up the given package
1043 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001044 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001045
Dan Egnor852f8e42009-09-30 11:20:45 -07001046 synchronized (mEverStoredApps) {
1047 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1048 // we'll recognize on initialization time that the package no longer
1049 // exists and fix it up then.
1050 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1051 RandomAccessFile known = null;
1052 try {
1053 known = new RandomAccessFile(tempKnownFile, "rws");
1054 mEverStoredApps.remove(packageName);
1055 for (String s : mEverStoredApps) {
1056 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001057 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001058 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001059 known.close();
1060 known = null;
1061 if (!tempKnownFile.renameTo(mEverStored)) {
1062 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1063 }
1064 } catch (IOException e) {
1065 // Bad: we couldn't create the new copy. For safety's sake we
1066 // abandon the whole process and remove all what's-backed-up
1067 // state entirely, meaning we'll force a backup pass for every
1068 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001069 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001070 mEverStoredApps.clear();
1071 tempKnownFile.delete();
1072 mEverStored.delete();
1073 } finally {
1074 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001075 }
1076 }
1077 }
1078
Christopher Tateb49ceb32010-02-08 16:22:24 -08001079 // Persistently record the current and ancestral backup tokens as well
1080 // as the set of packages with data [supposedly] available in the
1081 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001082 void writeRestoreTokens() {
1083 try {
1084 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001085
1086 // First, the version number of this record, for futureproofing
1087 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1088
1089 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001090 af.writeLong(mAncestralToken);
1091 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001092
1093 // Now write the set of ancestral packages
1094 if (mAncestralPackages == null) {
1095 af.writeInt(-1);
1096 } else {
1097 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001098 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001099 for (String pkgName : mAncestralPackages) {
1100 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001101 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001102 }
1103 }
Christopher Tate84725812010-02-04 15:52:40 -08001104 af.close();
1105 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001106 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001107 }
1108 }
1109
Dan Egnor87a02bc2009-06-17 02:30:10 -07001110 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001111 private IBackupTransport getTransport(String transportName) {
1112 synchronized (mTransports) {
1113 IBackupTransport transport = mTransports.get(transportName);
1114 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001115 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001116 }
1117 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001118 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001119 }
1120
Christopher Tatedf01dea2009-06-09 20:45:02 -07001121 // fire off a backup agent, blocking until it attaches or times out
1122 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1123 IBackupAgent agent = null;
1124 synchronized(mAgentConnectLock) {
1125 mConnecting = true;
1126 mConnectedAgent = null;
1127 try {
1128 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001129 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001130
1131 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001132 // only wait 10 seconds for the clear data to happen
1133 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1134 while (mConnecting && mConnectedAgent == null
1135 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001136 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001137 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001138 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001139 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001140 return null;
1141 }
1142 }
1143
1144 // if we timed out with no connect, abort and move on
1145 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001146 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001147 return null;
1148 }
1149 agent = mConnectedAgent;
1150 }
1151 } catch (RemoteException e) {
1152 // can't happen
1153 }
1154 }
1155 return agent;
1156 }
1157
Christopher Tatec7b31e32009-06-10 15:49:30 -07001158 // clear an application's data, blocking until the operation completes or times out
1159 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001160 // Don't wipe packages marked allowClearUserData=false
1161 try {
1162 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1163 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001164 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001165 + packageName);
1166 return;
1167 }
1168 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001169 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001170 return;
1171 }
1172
Christopher Tatec7b31e32009-06-10 15:49:30 -07001173 ClearDataObserver observer = new ClearDataObserver();
1174
1175 synchronized(mClearDataLock) {
1176 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001177 try {
1178 mActivityManager.clearApplicationUserData(packageName, observer);
1179 } catch (RemoteException e) {
1180 // can't happen because the activity manager is in this process
1181 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001182
1183 // only wait 10 seconds for the clear data to happen
1184 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1185 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1186 try {
1187 mClearDataLock.wait(5000);
1188 } catch (InterruptedException e) {
1189 // won't happen, but still.
1190 mClearingData = false;
1191 }
1192 }
1193 }
1194 }
1195
1196 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001197 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001198 synchronized(mClearDataLock) {
1199 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001200 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001201 }
1202 }
1203 }
1204
Christopher Tate1bb69062010-02-19 17:02:12 -08001205 // Get the restore-set token for the best-available restore set for this package:
1206 // the active set if possible, else the ancestral one. Returns zero if none available.
1207 long getAvailableRestoreToken(String packageName) {
1208 long token = mAncestralToken;
1209 synchronized (mQueueLock) {
1210 if (mEverStoredApps.contains(packageName)) {
1211 token = mCurrentToken;
1212 }
1213 }
1214 return token;
1215 }
1216
Christopher Tate44a27902010-01-27 17:15:49 -08001217 // -----
1218 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1219 boolean waitUntilOperationComplete(int token) {
1220 int finalState = OP_PENDING;
1221 synchronized (mCurrentOpLock) {
1222 try {
1223 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1224 try {
1225 mCurrentOpLock.wait();
1226 } catch (InterruptedException e) {}
1227 }
1228 } catch (IndexOutOfBoundsException e) {
1229 // the operation has been mysteriously cleared from our
1230 // bookkeeping -- consider this a success and ignore it.
1231 }
1232 }
1233 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001234 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001235 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001236 return finalState == OP_ACKNOWLEDGED;
1237 }
1238
1239 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001240 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001241 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001242 mCurrentOperations.put(token, OP_PENDING);
1243 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1244 mBackupHandler.sendMessageDelayed(msg, interval);
1245 }
1246
Christopher Tate043dadc2009-06-02 16:11:00 -07001247 // ----- Back up a set of applications via a worker thread -----
1248
Christopher Tate44a27902010-01-27 17:15:49 -08001249 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001250 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001251 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001252 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001253 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001254 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001255
Christopher Tate44a27902010-01-27 17:15:49 -08001256 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001257 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001258 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001259 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001260 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001261
1262 try {
1263 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1264 } catch (RemoteException e) {
1265 // can't happen; the transport is local
1266 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001267 }
1268
Christopher Tate043dadc2009-06-02 16:11:00 -07001269 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001270 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001271 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001272 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001273
Christopher Tate79588342009-06-30 16:11:49 -07001274 // Backups run at background priority
1275 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1276
Christopher Tate043dadc2009-06-02 16:11:00 -07001277 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001278 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001279
Dan Egnor852f8e42009-09-30 11:20:45 -07001280 // If we haven't stored package manager metadata yet, we must init the transport.
1281 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1282 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001284 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001285 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001286 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001287 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001288 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001289 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001290 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001291 }
Dan Egnor01445162009-09-21 17:04:05 -07001292 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001293
1294 // The package manager doesn't have a proper <application> etc, but since
1295 // it's running here in the system process we can just set up its agent
1296 // directly and use a synthetic BackupRequest. We always run this pass
1297 // because it's cheap and this way we guarantee that we don't get out of
1298 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001299 if (status == BackupConstants.TRANSPORT_OK) {
1300 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1301 mPackageManager, allAgentPackages());
1302 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1303 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1304 status = processOneBackup(pmRequest,
1305 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1306 }
Christopher Tate90967f42009-09-20 15:28:33 -07001307
Dan Egnor01445162009-09-21 17:04:05 -07001308 if (status == BackupConstants.TRANSPORT_OK) {
1309 // Now run all the backups in our queue
1310 status = doQueuedBackups(mTransport);
1311 }
1312
1313 if (status == BackupConstants.TRANSPORT_OK) {
1314 // Tell the transport to finish everything it has buffered
1315 status = mTransport.finishBackup();
1316 if (status == BackupConstants.TRANSPORT_OK) {
1317 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001318 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001319 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001320 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001321 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001322 }
1323 }
1324
Dan Egnor01445162009-09-21 17:04:05 -07001325 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001326 // The backend reports that our dataset has been wiped. We need to
1327 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001328 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001329 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001330 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001331 }
1332 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001333 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001334 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001335 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001336 // If everything actually went through and this is the first time we've
1337 // done a backup, we can now record what the current backup dataset token
1338 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001339 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001340 try {
1341 mCurrentToken = mTransport.getCurrentRestoreSet();
1342 } catch (RemoteException e) { /* cannot happen */ }
1343 writeRestoreTokens();
1344 }
1345
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001346 // If things went wrong, we need to re-stage the apps we had expected
1347 // to be backing up in this pass. This journals the package names in
1348 // the current active pending-backup file, not in the we are holding
1349 // here in mJournal.
1350 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001351 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001352 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001353 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001354 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001355
1356 // We also want to reset the backup schedule based on whatever
1357 // the transport suggests by way of retry/backoff time.
1358 try {
1359 startBackupAlarmsLocked(mTransport.requestBackupTime());
1360 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001361 }
1362
1363 // Either backup was successful, in which case we of course do not need
1364 // this pass's journal any more; or it failed, in which case we just
1365 // re-enqueued all of these packages in the current active journal.
1366 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001367 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001368 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001369 }
1370
Christopher Tatec2af5d32010-02-02 15:18:58 -08001371 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001372 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001373 backupNow();
1374 }
1375
Dan Egnorbb9001c2009-07-27 12:20:13 -07001376 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001377 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 }
1379
Dan Egnor01445162009-09-21 17:04:05 -07001380 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001381 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001382 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001383
1384 IBackupAgent agent = null;
1385 int mode = (request.fullBackup)
1386 ? IApplicationThread.BACKUP_MODE_FULL
1387 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1388 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001389 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001390 agent = bindToAgentSynchronous(request.appInfo, mode);
1391 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001392 int result = processOneBackup(request, agent, transport);
1393 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001394 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001395 } catch (SecurityException ex) {
1396 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001398 } finally {
1399 try { // unbind even on timeout, just in case
1400 mActivityManager.unbindBackupAgent(request.appInfo);
1401 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001402 }
1403 }
Dan Egnor01445162009-09-21 17:04:05 -07001404
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001405 mWakelock.setWorkSource(null);
1406
Dan Egnor01445162009-09-21 17:04:05 -07001407 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001408 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001409
Dan Egnor01445162009-09-21 17:04:05 -07001410 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1411 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001412 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001413 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001414
Dan Egnorbb9001c2009-07-27 12:20:13 -07001415 File savedStateName = new File(mStateDir, packageName);
1416 File backupDataName = new File(mDataDir, packageName + ".data");
1417 File newStateName = new File(mStateDir, packageName + ".new");
1418
1419 ParcelFileDescriptor savedState = null;
1420 ParcelFileDescriptor backupData = null;
1421 ParcelFileDescriptor newState = null;
1422
1423 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001424 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001425 try {
1426 // Look up the package info & signatures. This is first so that if it
1427 // throws an exception, there's no file setup yet that would need to
1428 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001429 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1430 // The metadata 'package' is synthetic
1431 packInfo = new PackageInfo();
1432 packInfo.packageName = packageName;
1433 } else {
1434 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001435 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001436 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001437
Christopher Tatec7b31e32009-06-10 15:49:30 -07001438 // In a full backup, we pass a null ParcelFileDescriptor as
1439 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 if (!request.fullBackup) {
1441 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001442 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001443 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1444 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001445
Dan Egnorbb9001c2009-07-27 12:20:13 -07001446 backupData = ParcelFileDescriptor.open(backupDataName,
1447 ParcelFileDescriptor.MODE_READ_WRITE |
1448 ParcelFileDescriptor.MODE_CREATE |
1449 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001450
Dan Egnorbb9001c2009-07-27 12:20:13 -07001451 newState = ParcelFileDescriptor.open(newStateName,
1452 ParcelFileDescriptor.MODE_READ_WRITE |
1453 ParcelFileDescriptor.MODE_CREATE |
1454 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001455
Christopher Tate44a27902010-01-27 17:15:49 -08001456 // Initiate the target's backup pass
1457 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1458 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1459 boolean success = waitUntilOperationComplete(token);
1460
1461 if (!success) {
1462 // timeout -- bail out into the failed-transaction logic
1463 throw new RuntimeException("Backup timeout");
1464 }
1465
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001467 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001468 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001469 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001470 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 backupDataName.delete();
1472 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001473 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001474 } finally {
1475 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1476 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1477 try { if (newState != null) newState.close(); } catch (IOException e) {}
1478 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001479 synchronized (mCurrentOpLock) {
1480 mCurrentOperations.clear();
1481 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001482 }
1483
1484 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001485 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001486 try {
1487 int size = (int) backupDataName.length();
1488 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001489 if (result == BackupConstants.TRANSPORT_OK) {
1490 backupData = ParcelFileDescriptor.open(backupDataName,
1491 ParcelFileDescriptor.MODE_READ_ONLY);
1492 result = transport.performBackup(packInfo, backupData);
1493 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001494
Dan Egnor83861e72009-09-17 16:17:55 -07001495 // TODO - We call finishBackup() for each application backed up, because
1496 // we need to know now whether it succeeded or failed. Instead, we should
1497 // hold off on finishBackup() until the end, which implies holding off on
1498 // renaming *all* the output state files (see below) until that happens.
1499
Dan Egnor01445162009-09-21 17:04:05 -07001500 if (result == BackupConstants.TRANSPORT_OK) {
1501 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001502 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001503 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001504 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001505 }
1506
1507 // After successful transport, delete the now-stale data
1508 // and juggle the files so that next time we supply the agent
1509 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001510 if (result == BackupConstants.TRANSPORT_OK) {
1511 backupDataName.delete();
1512 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001513 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001514 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001515 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001516 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001517 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001518 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001519 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001520 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001521 } finally {
1522 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001523 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001524
Dan Egnor01445162009-09-21 17:04:05 -07001525 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001526 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001527 }
1528
Christopher Tatedf01dea2009-06-09 20:45:02 -07001529
1530 // ----- Restore handling -----
1531
Christopher Tate78dd4a72009-11-04 11:49:08 -08001532 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1533 // If the target resides on the system partition, we allow it to restore
1534 // data from the like-named package in a restore set even if the signatures
1535 // do not match. (Unlike general applications, those flashed to the system
1536 // partition will be signed with the device's platform certificate, so on
1537 // different phones the same system app will have different signatures.)
1538 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001540 return true;
1541 }
1542
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001543 // Allow unsigned apps, but not signed on one device and unsigned on the other
1544 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001545 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001547 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001548 if ((storedSigs == null || storedSigs.length == 0)
1549 && (deviceSigs == null || deviceSigs.length == 0)) {
1550 return true;
1551 }
1552 if (storedSigs == null || deviceSigs == null) {
1553 return false;
1554 }
1555
Christopher Tateabce4e82009-06-18 18:35:32 -07001556 // !!! TODO: this demands that every stored signature match one
1557 // that is present on device, and does not demand the converse.
1558 // Is this this right policy?
1559 int nStored = storedSigs.length;
1560 int nDevice = deviceSigs.length;
1561
1562 for (int i=0; i < nStored; i++) {
1563 boolean match = false;
1564 for (int j=0; j < nDevice; j++) {
1565 if (storedSigs[i].equals(deviceSigs[j])) {
1566 match = true;
1567 break;
1568 }
1569 }
1570 if (!match) {
1571 return false;
1572 }
1573 }
1574 return true;
1575 }
1576
Christopher Tate44a27902010-01-27 17:15:49 -08001577 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001578 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001579 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001580 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001581 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001582 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001583 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001584 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001585
Christopher Tate5cbbf562009-06-22 16:44:51 -07001586 class RestoreRequest {
1587 public PackageInfo app;
1588 public int storedAppVersion;
1589
1590 RestoreRequest(PackageInfo _app, int _version) {
1591 app = _app;
1592 storedAppVersion = _version;
1593 }
1594 }
1595
Christopher Tate44a27902010-01-27 17:15:49 -08001596 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001597 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1598 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001599 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001600 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001601 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001602 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001603 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001604 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001605
1606 try {
1607 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1608 } catch (RemoteException e) {
1609 // can't happen; the transport is local
1610 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001611 }
1612
Christopher Tatedf01dea2009-06-09 20:45:02 -07001613 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001615 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001616 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001617 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001618
Christopher Tateb49ceb32010-02-08 16:22:24 -08001619 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001620 int error = -1; // assume error
1621
Dan Egnorefe52642009-06-24 00:16:33 -07001622 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001623 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001624 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001625 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001626
Dan Egnorefe52642009-06-24 00:16:33 -07001627 // Get the list of all packages which have backup enabled.
1628 // (Include the Package Manager metadata pseudo-package first.)
1629 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1630 PackageInfo omPackage = new PackageInfo();
1631 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1632 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001633
Dan Egnorefe52642009-06-24 00:16:33 -07001634 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001635 if (mTargetPackage == null) {
1636 restorePackages.addAll(agentPackages);
1637 } else {
1638 // Just one package to attempt restore of
1639 restorePackages.add(mTargetPackage);
1640 }
Dan Egnorefe52642009-06-24 00:16:33 -07001641
Christopher Tate7d562ec2009-06-25 18:03:43 -07001642 // let the observer know that we're running
1643 if (mObserver != null) {
1644 try {
1645 // !!! TODO: get an actual count from the transport after
1646 // its startRestore() runs?
1647 mObserver.restoreStarting(restorePackages.size());
1648 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001649 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001650 mObserver = null;
1651 }
1652 }
1653
Dan Egnor01445162009-09-21 17:04:05 -07001654 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1655 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001656 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001657 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001658 return;
1659 }
1660
1661 String packageName = mTransport.nextRestorePackage();
1662 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001663 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001664 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001665 return;
1666 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001667 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001668 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001669 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001670 return;
1671 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001672 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001673 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001674 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001675 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001676 return;
1677 }
1678
1679 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001680 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001681 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07001682 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
1683 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07001684
Christopher Tate8c032472009-07-02 14:28:47 -07001685 // Verify that the backup set includes metadata. If not, we can't do
1686 // signature/version verification etc, so we simply do not proceed with
1687 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001688 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001689 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001690 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001691 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001692 return;
1693 }
1694
Christopher Tate7d562ec2009-06-25 18:03:43 -07001695 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001696 for (;;) {
1697 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001698
Dan Egnorefe52642009-06-24 00:16:33 -07001699 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001700 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001701 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001702 return;
1703 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001704 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001705 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001706 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001707
Christopher Tate7d562ec2009-06-25 18:03:43 -07001708 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001709 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001710 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001711 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001712 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001713 mObserver = null;
1714 }
1715 }
1716
Dan Egnorefe52642009-06-24 00:16:33 -07001717 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1718 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001719 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001720 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001721 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001722 continue;
1723 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001724
Dan Egnorbb9001c2009-07-27 12:20:13 -07001725 PackageInfo packageInfo;
1726 try {
1727 int flags = PackageManager.GET_SIGNATURES;
1728 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1729 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001730 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001731 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001732 "Package missing on device");
1733 continue;
1734 }
1735
Dan Egnorefe52642009-06-24 00:16:33 -07001736 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001737 // Data is from a "newer" version of the app than we have currently
1738 // installed. If the app has not declared that it is prepared to
1739 // handle this case, we do not attempt the restore.
1740 if ((packageInfo.applicationInfo.flags
1741 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1742 String message = "Version " + metaInfo.versionCode
1743 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001744 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001745 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1746 packageName, message);
1747 continue;
1748 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001749 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001750 + " > installed " + packageInfo.versionCode
1751 + " but restoreAnyVersion");
1752 }
Dan Egnorefe52642009-06-24 00:16:33 -07001753 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001754
Christopher Tate78dd4a72009-11-04 11:49:08 -08001755 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001756 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001757 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001758 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001759 continue;
1760 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001761
Joe Onorato8a9b2202010-02-26 18:56:32 -08001762 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001763 + " restore version [" + metaInfo.versionCode
1764 + "] is compatible with installed version ["
1765 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001766
Christopher Tate3de55bc2010-03-12 17:28:08 -08001767 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001768 IBackupAgent agent = bindToAgentSynchronous(
1769 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001770 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001771 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001772 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001773 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001774 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001775 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001776 }
1777
Christopher Tate5e1ab332009-09-01 20:32:49 -07001778 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001779 try {
Chris Tate249345b2010-10-29 12:57:04 -07001780 processOneRestore(packageInfo, metaInfo.versionCode, agent,
1781 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001782 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001783 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001784 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001785 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001786
1787 // The agent was probably running with a stub Application object,
1788 // which isn't a valid run mode for the main app logic. Shut
1789 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001790 // usual full initialization. Note that this is only done for
1791 // full-system restores: when a single app has requested a restore,
1792 // it is explicitly not killed following that operation.
1793 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001794 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001795 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001796 + packageInfo.applicationInfo.processName);
1797 mActivityManager.killApplicationProcess(
1798 packageInfo.applicationInfo.processName,
1799 packageInfo.applicationInfo.uid);
1800 }
Dan Egnorefe52642009-06-24 00:16:33 -07001801 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001802 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001803
1804 // if we get this far, report success to the observer
1805 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001806 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001807 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001808 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001810 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001811 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001812
Dan Egnorefe52642009-06-24 00:16:33 -07001813 try {
1814 mTransport.finishRestore();
1815 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001816 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001817 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001818
1819 if (mObserver != null) {
1820 try {
1821 mObserver.restoreFinished(error);
1822 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001823 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001824 }
1825 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001826
Christopher Tate84725812010-02-04 15:52:40 -08001827 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001828 // ancestral dataset, as well as the set of apps that are possibly
1829 // restoreable from the dataset
1830 if (mTargetPackage == null && pmAgent != null) {
1831 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001832 mAncestralToken = mToken;
1833 writeRestoreTokens();
1834 }
1835
Christopher Tate1bb69062010-02-19 17:02:12 -08001836 // We must under all circumstances tell the Package Manager to
1837 // proceed with install notifications if it's waiting for us.
1838 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001840 try {
1841 mPackageManagerBinder.finishPackageInstall(mPmToken);
1842 } catch (RemoteException e) { /* can't happen */ }
1843 }
1844
Christopher Tate73a3cb32010-12-13 18:27:26 -08001845 // Furthermore we need to reset the session timeout clock
1846 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
1847 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
1848 TIMEOUT_RESTORE_INTERVAL);
1849
Christopher Tateb6787f22009-07-02 17:40:45 -07001850 // done; we can finally release the wakelock
1851 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001852 }
1853 }
1854
Dan Egnorefe52642009-06-24 00:16:33 -07001855 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07001856 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
1857 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001858 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001859 final String packageName = app.packageName;
1860
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001862
Christopher Tatec7b31e32009-06-10 15:49:30 -07001863 // !!! TODO: get the dirs from the transport
1864 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001865 File newStateName = new File(mStateDir, packageName + ".new");
1866 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001867
Dan Egnorbb9001c2009-07-27 12:20:13 -07001868 ParcelFileDescriptor backupData = null;
1869 ParcelFileDescriptor newState = null;
1870
Christopher Tate44a27902010-01-27 17:15:49 -08001871 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001872 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001873 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001874 backupData = ParcelFileDescriptor.open(backupDataName,
1875 ParcelFileDescriptor.MODE_READ_WRITE |
1876 ParcelFileDescriptor.MODE_CREATE |
1877 ParcelFileDescriptor.MODE_TRUNCATE);
1878
Dan Egnor01445162009-09-21 17:04:05 -07001879 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001880 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001881 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001882 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001883 }
1884
1885 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001886 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001887 backupData = ParcelFileDescriptor.open(backupDataName,
1888 ParcelFileDescriptor.MODE_READ_ONLY);
1889
Dan Egnorbb9001c2009-07-27 12:20:13 -07001890 newState = ParcelFileDescriptor.open(newStateName,
1891 ParcelFileDescriptor.MODE_READ_WRITE |
1892 ParcelFileDescriptor.MODE_CREATE |
1893 ParcelFileDescriptor.MODE_TRUNCATE);
1894
Christopher Tate44a27902010-01-27 17:15:49 -08001895 // Kick off the restore, checking for hung agents
1896 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1897 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1898 boolean success = waitUntilOperationComplete(token);
1899
1900 if (!success) {
1901 throw new RuntimeException("restore timeout");
1902 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001903
1904 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001905 //
1906 // !!! TODO: the restored data should be migrated on the server
1907 // side into the current dataset. In that case the new state file
1908 // we just created would reflect the data already extant in the
1909 // backend, so there'd be nothing more to do. Until that happens,
1910 // however, we need to make sure that we record the data to the
1911 // current backend dataset. (Yes, this means shipping the data over
1912 // the wire in both directions. That's bad, but consistency comes
1913 // first, then efficiency.) Once we introduce server-side data
1914 // migration to the newly-restored device's dataset, we will change
1915 // the following from a discard of the newly-written state to the
1916 // "correct" operation of renaming into the canonical state blob.
1917 newStateName.delete(); // TODO: remove; see above comment
1918 //newStateName.renameTo(savedStateName); // TODO: replace with this
1919
Dan Egnorbb9001c2009-07-27 12:20:13 -07001920 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001921 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001922 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001923 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001924 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001925
Christopher Tate96733042009-07-20 14:49:13 -07001926 // If the agent fails restore, it might have put the app's data
1927 // into an incoherent state. For consistency we wipe its data
1928 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001929 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001930 } finally {
1931 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001932 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1933 try { if (newState != null) newState.close(); } catch (IOException e) {}
1934 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001935 mCurrentOperations.delete(token);
Chris Tate249345b2010-10-29 12:57:04 -07001936
1937 // If we know a priori that we'll need to perform a full post-restore backup
1938 // pass, clear the new state file data. This means we're discarding work that
1939 // was just done by the app's agent, but this way the agent doesn't need to
1940 // take any special action based on global device state.
1941 if (needFullBackup) {
1942 newStateName.delete();
1943 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001944 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001945 }
1946 }
1947
Christopher Tate44a27902010-01-27 17:15:49 -08001948 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001949 IBackupTransport mTransport;
1950 PackageInfo mPackage;
1951
Christopher Tate44a27902010-01-27 17:15:49 -08001952 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001953 mTransport = transport;
1954 mPackage = packageInfo;
1955 }
1956
Christopher Tateee0e78a2009-07-02 11:17:03 -07001957 public void run() {
1958 try {
1959 // Clear the on-device backup state to ensure a full backup next time
1960 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1961 File stateFile = new File(stateDir, mPackage.packageName);
1962 stateFile.delete();
1963
1964 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001965 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001966 mTransport.clearBackupData(mPackage);
1967 } catch (RemoteException e) {
1968 // can't happen; the transport is local
1969 } finally {
1970 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001971 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001972 mTransport.finishBackup();
1973 } catch (RemoteException e) {
1974 // can't happen; the transport is local
1975 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001976
1977 // Last but not least, release the cpu
1978 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001979 }
1980 }
1981 }
1982
Christopher Tate44a27902010-01-27 17:15:49 -08001983 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001984 HashSet<String> mQueue;
1985
Christopher Tate44a27902010-01-27 17:15:49 -08001986 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001987 mQueue = transportNames;
1988 }
1989
Christopher Tate4cc86e12009-09-21 19:36:51 -07001990 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001991 try {
1992 for (String transportName : mQueue) {
1993 IBackupTransport transport = getTransport(transportName);
1994 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001995 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001996 continue;
1997 }
1998
Joe Onorato8a9b2202010-02-26 18:56:32 -08001999 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002000 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002001 long startRealtime = SystemClock.elapsedRealtime();
2002 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002003
Christopher Tate4cc86e12009-09-21 19:36:51 -07002004 if (status == BackupConstants.TRANSPORT_OK) {
2005 status = transport.finishBackup();
2006 }
2007
2008 // Okay, the wipe really happened. Clean up our local bookkeeping.
2009 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002010 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002011 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002012 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002013 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002014 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002015 synchronized (mQueueLock) {
2016 recordInitPendingLocked(false, transportName);
2017 }
Dan Egnor726247c2009-09-29 19:12:31 -07002018 } else {
2019 // If this didn't work, requeue this one and try again
2020 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002021 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002023 synchronized (mQueueLock) {
2024 recordInitPendingLocked(true, transportName);
2025 }
2026 // do this via another alarm to make sure of the wakelock states
2027 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002028 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002029 + transportName + " resched in " + delay);
2030 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2031 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002032 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002033 }
2034 } catch (RemoteException e) {
2035 // can't happen; the transports are local
2036 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002037 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002038 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002039 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002040 mWakelock.release();
2041 }
2042 }
2043 }
2044
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002045 private void dataChangedImpl(String packageName) {
2046 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2047 dataChangedImpl(packageName, targets);
2048 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002049
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002050 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002051 // Record that we need a backup pass for the caller. Since multiple callers
2052 // may share a uid, we need to note all candidates within that uid and schedule
2053 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002054 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002055
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002056 if (targets == null) {
2057 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2058 + " uid=" + Binder.getCallingUid());
2059 return;
2060 }
2061
2062 synchronized (mQueueLock) {
2063 // Note that this client has made data changes that need to be backed up
2064 for (ApplicationInfo app : targets) {
2065 // validate the caller-supplied package name against the known set of
2066 // packages associated with this uid
2067 if (app.packageName.equals(packageName)) {
2068 // Add the caller to the set of pending backups. If there is
2069 // one already there, then overwrite it, but no harm done.
2070 BackupRequest req = new BackupRequest(app, false);
2071 if (mPendingBackups.put(app, req) == null) {
2072 // Journal this request in case of crash. The put()
2073 // operation returned null when this package was not already
2074 // in the set; we want to avoid touching the disk redundantly.
2075 writeToJournalLocked(packageName);
2076
2077 if (DEBUG) {
2078 int numKeys = mPendingBackups.size();
2079 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2080 for (BackupRequest b : mPendingBackups.values()) {
2081 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2082 }
2083 }
2084 }
2085 }
2086 }
2087 }
2088 }
2089
2090 // Note: packageName is currently unused, but may be in the future
2091 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002092 // If the caller does not hold the BACKUP permission, it can only request a
2093 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002094 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002095 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002096 synchronized (mBackupParticipants) {
2097 return mBackupParticipants.get(Binder.getCallingUid());
2098 }
2099 }
2100
2101 // a caller with full permission can ask to back up any participating app
2102 // !!! TODO: allow backup of ANY app?
2103 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2104 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002105 int N = mBackupParticipants.size();
2106 for (int i = 0; i < N; i++) {
2107 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2108 if (s != null) {
2109 targets.addAll(s);
2110 }
2111 }
2112 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002113 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002114 }
Christopher Tate46758122009-05-06 11:22:00 -07002115
Christopher Tatecde87f42009-06-12 12:55:53 -07002116 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002117 RandomAccessFile out = null;
2118 try {
2119 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2120 out = new RandomAccessFile(mJournal, "rws");
2121 out.seek(out.length());
2122 out.writeUTF(str);
2123 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002124 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002125 mJournal = null;
2126 } finally {
2127 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002128 }
2129 }
2130
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002131 // ----- IBackupManager binder interface -----
2132
2133 public void dataChanged(final String packageName) {
2134 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2135 if (targets == null) {
2136 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2137 + " uid=" + Binder.getCallingUid());
2138 return;
2139 }
2140
2141 mBackupHandler.post(new Runnable() {
2142 public void run() {
2143 dataChangedImpl(packageName, targets);
2144 }
2145 });
2146 }
2147
Christopher Tateee0e78a2009-07-02 11:17:03 -07002148 // Clear the given package's backup data from the current transport
2149 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002150 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002151 PackageInfo info;
2152 try {
2153 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2154 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002155 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002156 return;
2157 }
2158
2159 // If the caller does not hold the BACKUP permission, it can only request a
2160 // wipe of its own backed-up data.
2161 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002162 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002163 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2164 apps = mBackupParticipants.get(Binder.getCallingUid());
2165 } else {
2166 // a caller with full permission can ask to back up any participating app
2167 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002168 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002169 apps = new HashSet<ApplicationInfo>();
2170 int N = mBackupParticipants.size();
2171 for (int i = 0; i < N; i++) {
2172 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2173 if (s != null) {
2174 apps.addAll(s);
2175 }
2176 }
2177 }
2178
2179 // now find the given package in the set of candidate apps
2180 for (ApplicationInfo app : apps) {
2181 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002182 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002183 // found it; fire off the clear request
2184 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002185 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002186 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002187 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2188 new ClearParams(getTransport(mCurrentTransport), info));
2189 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002190 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002191 }
2192 break;
2193 }
2194 }
2195 }
2196
Christopher Tateace7f092009-06-15 18:07:25 -07002197 // Run a backup pass immediately for any applications that have declared
2198 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002199 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002200 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002201
Joe Onorato8a9b2202010-02-26 18:56:32 -08002202 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002203 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002204 // Because the alarms we are using can jitter, and we want an *immediate*
2205 // backup pass to happen, we restart the timer beginning with "next time,"
2206 // then manually fire the backup trigger intent ourselves.
2207 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002208 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002209 mRunBackupIntent.send();
2210 } catch (PendingIntent.CanceledException e) {
2211 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002212 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002213 }
Christopher Tate46758122009-05-06 11:22:00 -07002214 }
2215 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002216
Christopher Tate8031a3d2009-07-06 16:36:05 -07002217 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002218 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002219 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2220 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002221
Joe Onorato8a9b2202010-02-26 18:56:32 -08002222 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002223
Christopher Tate6ef58a12009-06-29 14:56:28 -07002224 boolean wasEnabled = mEnabled;
2225 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002226 Settings.Secure.putInt(mContext.getContentResolver(),
2227 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002228 mEnabled = enable;
2229 }
2230
Christopher Tate49401dd2009-07-01 12:34:29 -07002231 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002232 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002233 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002234 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002235 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002236 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002238
Christopher Tateb6787f22009-07-02 17:40:45 -07002239 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002240
2241 // This also constitutes an opt-out, so we wipe any data for
2242 // this device from the backend. We start that process with
2243 // an alarm in order to guarantee wakelock states.
2244 if (wasEnabled && mProvisioned) {
2245 // NOTE: we currently flush every registered transport, not just
2246 // the currently-active one.
2247 HashSet<String> allTransports;
2248 synchronized (mTransports) {
2249 allTransports = new HashSet<String>(mTransports.keySet());
2250 }
2251 // build the set of transports for which we are posting an init
2252 for (String transport : allTransports) {
2253 recordInitPendingLocked(true, transport);
2254 }
2255 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2256 mRunInitIntent);
2257 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002258 }
2259 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002260 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002261
Christopher Tatecce9da52010-02-03 15:11:15 -08002262 // Enable/disable automatic restore of app data at install time
2263 public void setAutoRestore(boolean doAutoRestore) {
2264 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2265 "setBackupEnabled");
2266
Joe Onorato8a9b2202010-02-26 18:56:32 -08002267 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002268
2269 synchronized (this) {
2270 Settings.Secure.putInt(mContext.getContentResolver(),
2271 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2272 mAutoRestore = doAutoRestore;
2273 }
2274 }
2275
Christopher Tate8031a3d2009-07-06 16:36:05 -07002276 // Mark the backup service as having been provisioned
2277 public void setBackupProvisioned(boolean available) {
2278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2279 "setBackupProvisioned");
2280
2281 boolean wasProvisioned = mProvisioned;
2282 synchronized (this) {
2283 Settings.Secure.putInt(mContext.getContentResolver(),
2284 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2285 mProvisioned = available;
2286 }
2287
2288 synchronized (mQueueLock) {
2289 if (available && !wasProvisioned && mEnabled) {
2290 // we're now good to go, so start the backup alarms
2291 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2292 } else if (!available) {
2293 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002294 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002295 mAlarmManager.cancel(mRunBackupIntent);
2296 }
2297 }
2298 }
2299
2300 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002301 // We used to use setInexactRepeating(), but that may be linked to
2302 // backups running at :00 more often than not, creating load spikes.
2303 // Schedule at an exact time for now, and also add a bit of "fuzz".
2304
2305 Random random = new Random();
2306 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2307 random.nextInt(FUZZ_MILLIS);
2308 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2309 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002310 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002311 }
2312
Christopher Tate6ef58a12009-06-29 14:56:28 -07002313 // Report whether the backup mechanism is currently enabled
2314 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002316 return mEnabled; // no need to synchronize just to read it
2317 }
2318
Christopher Tate91717492009-06-26 21:07:13 -07002319 // Report the name of the currently active transport
2320 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002321 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002322 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002323 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002324 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002325 }
2326
Christopher Tate91717492009-06-26 21:07:13 -07002327 // Report all known, available backup transports
2328 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002329 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002330
Christopher Tate91717492009-06-26 21:07:13 -07002331 String[] list = null;
2332 ArrayList<String> known = new ArrayList<String>();
2333 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2334 if (entry.getValue() != null) {
2335 known.add(entry.getKey());
2336 }
2337 }
2338
2339 if (known.size() > 0) {
2340 list = new String[known.size()];
2341 known.toArray(list);
2342 }
2343 return list;
2344 }
2345
2346 // Select which transport to use for the next backup operation. If the given
2347 // name is not one of the available transports, no action is taken and the method
2348 // returns null.
2349 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002351
2352 synchronized (mTransports) {
2353 String prevTransport = null;
2354 if (mTransports.get(transport) != null) {
2355 prevTransport = mCurrentTransport;
2356 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002357 Settings.Secure.putString(mContext.getContentResolver(),
2358 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002359 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002360 + " returning " + prevTransport);
2361 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002362 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002363 }
2364 return prevTransport;
2365 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002366 }
2367
Christopher Tatef5e1c292010-12-08 18:40:26 -08002368 // Supply the configuration Intent for the given transport. If the name is not one
2369 // of the available transports, or if the transport does not supply any configuration
2370 // UI, the method returns null.
2371 public Intent getConfigurationIntent(String transportName) {
2372 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2373 "getConfigurationIntent");
2374
2375 synchronized (mTransports) {
2376 final IBackupTransport transport = mTransports.get(transportName);
2377 if (transport != null) {
2378 try {
2379 final Intent intent = transport.configurationIntent();
2380 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2381 + intent);
2382 return intent;
2383 } catch (RemoteException e) {
2384 /* fall through to return null */
2385 }
2386 }
2387 }
2388
2389 return null;
2390 }
2391
2392 // Supply the configuration summary string for the given transport. If the name is
2393 // not one of the available transports, or if the transport does not supply any
2394 // summary / destination string, the method can return null.
2395 //
2396 // This string is used VERBATIM as the summary text of the relevant Settings item!
2397 public String getDestinationString(String transportName) {
2398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2399 "getConfigurationIntent");
2400
2401 synchronized (mTransports) {
2402 final IBackupTransport transport = mTransports.get(transportName);
2403 if (transport != null) {
2404 try {
2405 final String text = transport.currentDestinationString();
2406 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2407 return text;
2408 } catch (RemoteException e) {
2409 /* fall through to return null */
2410 }
2411 }
2412 }
2413
2414 return null;
2415 }
2416
Christopher Tate043dadc2009-06-02 16:11:00 -07002417 // Callback: a requested backup agent has been instantiated. This should only
2418 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002419 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002420 synchronized(mAgentConnectLock) {
2421 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002422 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002423 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2424 mConnectedAgent = agent;
2425 mConnecting = false;
2426 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002427 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002428 + " claiming agent connected");
2429 }
2430 mAgentConnectLock.notifyAll();
2431 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002432 }
2433
2434 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2435 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002436 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002437 public void agentDisconnected(String packageName) {
2438 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002439 synchronized(mAgentConnectLock) {
2440 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2441 mConnectedAgent = null;
2442 mConnecting = false;
2443 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002444 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002445 + " claiming agent disconnected");
2446 }
2447 mAgentConnectLock.notifyAll();
2448 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002449 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002450
Christopher Tate1bb69062010-02-19 17:02:12 -08002451 // An application being installed will need a restore pass, then the Package Manager
2452 // will need to be told when the restore is finished.
2453 public void restoreAtInstall(String packageName, int token) {
2454 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002455 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002456 + " attemping install-time restore");
2457 return;
2458 }
2459
2460 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002461 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002462 + " token=" + Integer.toHexString(token));
2463
Christopher Tatef0872722010-02-25 15:22:48 -08002464 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002465 // okay, we're going to attempt a restore of this package from this restore set.
2466 // The eventual message back into the Package Manager to run the post-install
2467 // steps for 'token' will be issued from the restore handling code.
2468
2469 // We can use a synthetic PackageInfo here because:
2470 // 1. We know it's valid, since the Package Manager supplied the name
2471 // 2. Only the packageName field will be used by the restore code
2472 PackageInfo pkg = new PackageInfo();
2473 pkg.packageName = packageName;
2474
2475 mWakelock.acquire();
2476 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2477 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002478 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002479 mBackupHandler.sendMessage(msg);
2480 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002481 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2482 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002483 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002484 try {
2485 mPackageManagerBinder.finishPackageInstall(token);
2486 } catch (RemoteException e) { /* can't happen */ }
2487 }
2488 }
2489
Christopher Tate8c850b72009-06-07 19:33:20 -07002490 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002491 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2492 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2493 + " transport=" + transport);
2494
2495 boolean needPermission = true;
2496 if (transport == null) {
2497 transport = mCurrentTransport;
2498
2499 if (packageName != null) {
2500 PackageInfo app = null;
2501 try {
2502 app = mPackageManager.getPackageInfo(packageName, 0);
2503 } catch (NameNotFoundException nnf) {
2504 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2505 throw new IllegalArgumentException("Package " + packageName + " not found");
2506 }
2507
2508 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2509 // So: using the current active transport, and the caller has asked
2510 // that its own package will be restored. In this narrow use case
2511 // we do not require the caller to hold the permission.
2512 needPermission = false;
2513 }
2514 }
2515 }
2516
2517 if (needPermission) {
2518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2519 "beginRestoreSession");
2520 } else {
2521 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2522 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002523
2524 synchronized(this) {
2525 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002526 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002527 return null;
2528 }
Chris Tate44ab8452010-11-16 15:10:49 -08002529 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08002530 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07002531 }
2532 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002533 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002534
Christopher Tate73a3cb32010-12-13 18:27:26 -08002535 void clearRestoreSession(ActiveRestoreSession currentSession) {
2536 synchronized(this) {
2537 if (currentSession != mActiveRestoreSession) {
2538 Slog.e(TAG, "ending non-current restore session");
2539 } else {
2540 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
2541 mActiveRestoreSession = null;
2542 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2543 }
2544 }
2545 }
2546
Christopher Tate44a27902010-01-27 17:15:49 -08002547 // Note that a currently-active backup agent has notified us that it has
2548 // completed the given outstanding asynchronous backup/restore operation.
2549 public void opComplete(int token) {
2550 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002551 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002552 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2553 mCurrentOpLock.notifyAll();
2554 }
2555 }
2556
Christopher Tate9b3905c2009-06-08 15:24:01 -07002557 // ----- Restore session -----
2558
Christopher Tate80202c82010-01-25 19:37:47 -08002559 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002560 private static final String TAG = "RestoreSession";
2561
Chris Tate44ab8452010-11-16 15:10:49 -08002562 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002563 private IBackupTransport mRestoreTransport = null;
2564 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08002565 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002566
Chris Tate44ab8452010-11-16 15:10:49 -08002567 ActiveRestoreSession(String packageName, String transport) {
2568 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07002569 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002570 }
2571
2572 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002573 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002574 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002575 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002576 if (observer == null) {
2577 throw new IllegalArgumentException("Observer must not be null");
2578 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002579
Christopher Tate73a3cb32010-12-13 18:27:26 -08002580 if (mEnded) {
2581 throw new IllegalStateException("Restore session already ended");
2582 }
2583
Christopher Tate1bb69062010-02-19 17:02:12 -08002584 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002585 try {
Christopher Tate43383042009-07-13 15:17:13 -07002586 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002587 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002588 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002589 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002590 // spin off the transport request to our service thread
2591 mWakelock.acquire();
2592 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2593 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2594 mBackupHandler.sendMessage(msg);
2595 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002596 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002597 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002598 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002599 } finally {
2600 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002601 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002602 }
2603
Christopher Tate84725812010-02-04 15:52:40 -08002604 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002605 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2606 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002607
Chris Tate44ab8452010-11-16 15:10:49 -08002608 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002609 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002610
Christopher Tate73a3cb32010-12-13 18:27:26 -08002611 if (mEnded) {
2612 throw new IllegalStateException("Restore session already ended");
2613 }
2614
Dan Egnor0084da52009-07-29 12:57:16 -07002615 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08002616 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
2617 return -1;
2618 }
2619
2620 if (mPackageName != null) {
2621 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07002622 return -1;
2623 }
2624
Christopher Tate21ab6a52009-09-24 18:01:46 -07002625 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002626 for (int i = 0; i < mRestoreSets.length; i++) {
2627 if (token == mRestoreSets[i].token) {
2628 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002629 mWakelock.acquire();
2630 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002631 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07002632 mBackupHandler.sendMessage(msg);
2633 Binder.restoreCallingIdentity(oldId);
2634 return 0;
2635 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002636 }
2637 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002638
Joe Onorato8a9b2202010-02-26 18:56:32 -08002639 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002640 return -1;
2641 }
2642
Christopher Tate84725812010-02-04 15:52:40 -08002643 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002644 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002645
Christopher Tate73a3cb32010-12-13 18:27:26 -08002646 if (mEnded) {
2647 throw new IllegalStateException("Restore session already ended");
2648 }
2649
Chris Tate44ab8452010-11-16 15:10:49 -08002650 if (mPackageName != null) {
2651 if (! mPackageName.equals(packageName)) {
2652 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
2653 + " on session for package " + mPackageName);
2654 return -1;
2655 }
2656 }
2657
Christopher Tate84725812010-02-04 15:52:40 -08002658 PackageInfo app = null;
2659 try {
2660 app = mPackageManager.getPackageInfo(packageName, 0);
2661 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002662 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002663 return -1;
2664 }
2665
2666 // If the caller is not privileged and is not coming from the target
2667 // app's uid, throw a permission exception back to the caller.
2668 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2669 Binder.getCallingPid(), Binder.getCallingUid());
2670 if ((perm == PackageManager.PERMISSION_DENIED) &&
2671 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002672 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002673 + " or calling uid=" + Binder.getCallingUid());
2674 throw new SecurityException("No permission to restore other packages");
2675 }
2676
Christopher Tate7d411a32010-02-26 11:27:08 -08002677 // If the package has no backup agent, we obviously cannot proceed
2678 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002679 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002680 return -1;
2681 }
2682
Christopher Tate84725812010-02-04 15:52:40 -08002683 // So far so good; we're allowed to try to restore this package. Now
2684 // check whether there is data for it in the current dataset, falling back
2685 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002686 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002687
2688 // If we didn't come up with a place to look -- no ancestral dataset and
2689 // the app has never been backed up from this device -- there's nothing
2690 // to do but return failure.
2691 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08002692 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08002693 return -1;
2694 }
2695
2696 // Ready to go: enqueue the restore request and claim success
2697 long oldId = Binder.clearCallingIdentity();
2698 mWakelock.acquire();
2699 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002700 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08002701 mBackupHandler.sendMessage(msg);
2702 Binder.restoreCallingIdentity(oldId);
2703 return 0;
2704 }
2705
Christopher Tate73a3cb32010-12-13 18:27:26 -08002706 // Posted to the handler to tear down a restore session in a cleanly synchronized way
2707 class EndRestoreRunnable implements Runnable {
2708 BackupManagerService mBackupManager;
2709 ActiveRestoreSession mSession;
2710
2711 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
2712 mBackupManager = manager;
2713 mSession = session;
2714 }
2715
2716 public void run() {
2717 // clean up the session's bookkeeping
2718 synchronized (mSession) {
2719 try {
2720 if (mSession.mRestoreTransport != null) {
2721 mSession.mRestoreTransport.finishRestore();
2722 }
2723 } catch (Exception e) {
2724 Slog.e(TAG, "Error in finishRestore", e);
2725 } finally {
2726 mSession.mRestoreTransport = null;
2727 mSession.mEnded = true;
2728 }
2729 }
2730
2731 // clean up the BackupManagerService side of the bookkeeping
2732 // and cancel any pending timeout message
2733 mBackupManager.clearRestoreSession(mSession);
2734 }
2735 }
2736
Dan Egnor0084da52009-07-29 12:57:16 -07002737 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002738 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002739
Christopher Tate73a3cb32010-12-13 18:27:26 -08002740 if (mEnded) {
2741 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07002742 }
2743
Christopher Tate73a3cb32010-12-13 18:27:26 -08002744 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07002745 }
2746 }
2747
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002748 @Override
2749 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2750 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002751 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002752 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002753 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002754 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002755 pw.println("Last backup pass: " + mLastBackupPass
2756 + " (now = " + System.currentTimeMillis() + ')');
2757 pw.println(" next scheduled: " + mNextBackupPass);
2758
Christopher Tate91717492009-06-26 21:07:13 -07002759 pw.println("Available transports:");
2760 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002761 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2762 try {
2763 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2764 for (File f : dir.listFiles()) {
2765 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2766 }
2767 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002768 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002769 pw.println(" Error: " + e);
2770 }
Christopher Tate91717492009-06-26 21:07:13 -07002771 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002772
2773 pw.println("Pending init: " + mPendingInits.size());
2774 for (String s : mPendingInits) {
2775 pw.println(" " + s);
2776 }
2777
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002778 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002779 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002780 for (int i=0; i<N; i++) {
2781 int uid = mBackupParticipants.keyAt(i);
2782 pw.print(" uid: ");
2783 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002784 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2785 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002786 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002787 }
2788 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002789
Christopher Tateb49ceb32010-02-08 16:22:24 -08002790 pw.println("Ancestral packages: "
2791 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002792 if (mAncestralPackages != null) {
2793 for (String pkg : mAncestralPackages) {
2794 pw.println(" " + pkg);
2795 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002796 }
2797
Christopher Tate73e02522009-07-15 14:18:26 -07002798 pw.println("Ever backed up: " + mEverStoredApps.size());
2799 for (String pkg : mEverStoredApps) {
2800 pw.println(" " + pkg);
2801 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002802
2803 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002804 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002805 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002806 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002807 }
2808 }
Christopher Tate487529a2009-04-29 14:03:25 -07002809}