blob: ea38fbbeea418286f42824cd59899b42d49e29f0 [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;
Jason parksa3cdaa52011-01-13 14:15:43 -060026import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080027import 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;
Jason parks1125d782011-01-12 09:47:26 -060041import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060042import 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
Jason parksa3cdaa52011-01-13 14:15:43 -060064import com.android.internal.backup.BackupConstants;
65import com.android.internal.backup.IBackupTransport;
66import com.android.internal.backup.LocalTransport;
67import com.android.server.PackageManagerBackupAgent.Metadata;
68
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";
Christopher Tate994ef922011-01-12 20:06:07 -080087 private static final boolean DEBUG = false;
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 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800152 // Backups that we haven't started yet. Keys are package names.
153 HashMap<String,BackupRequest> mPendingBackups
154 = new HashMap<String,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
Christopher Tate2a935092011-03-03 17:30:32 -0800382 // Done: reset the session timeout clock
383 removeMessages(MSG_RESTORE_TIMEOUT);
384 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
385
Christopher Tate2d449afe2010-03-29 19:14:24 -0700386 mWakelock.release();
387 }
388 break;
389 }
390
Christopher Tate44a27902010-01-27 17:15:49 -0800391 case MSG_TIMEOUT:
392 {
393 synchronized (mCurrentOpLock) {
394 final int token = msg.arg1;
395 int state = mCurrentOperations.get(token, OP_TIMEOUT);
396 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800397 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800398 mCurrentOperations.put(token, OP_TIMEOUT);
399 }
400 mCurrentOpLock.notifyAll();
401 }
402 break;
403 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800404
405 case MSG_RESTORE_TIMEOUT:
406 {
407 synchronized (BackupManagerService.this) {
408 if (mActiveRestoreSession != null) {
409 // Client app left the restore session dangling. We know that it
410 // can't be in the middle of an actual restore operation because
411 // those are executed serially on this same handler thread. Clean
412 // up now.
413 Slog.w(TAG, "Restore session timed out; aborting");
414 post(mActiveRestoreSession.new EndRestoreRunnable(
415 BackupManagerService.this, mActiveRestoreSession));
416 }
417 }
418 }
Christopher Tate44a27902010-01-27 17:15:49 -0800419 }
420 }
421 }
422
423 // ----- Main service implementation -----
424
Christopher Tate487529a2009-04-29 14:03:25 -0700425 public BackupManagerService(Context context) {
426 mContext = context;
427 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700428 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700429 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700430
Christopher Tateb6787f22009-07-02 17:40:45 -0700431 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
432 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
433
Christopher Tate44a27902010-01-27 17:15:49 -0800434 mBackupManagerBinder = asInterface(asBinder());
435
436 // spin up the backup/restore handler thread
437 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
438 mHandlerThread.start();
439 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
440
Christopher Tate22b87872009-05-04 16:41:53 -0700441 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700442 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700443 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700444 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700445 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800446 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800447 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800448 // If Encrypted file systems is enabled or disabled, this call will return the
449 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600450 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800451 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700452 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700453
Christopher Tate4cc86e12009-09-21 19:36:51 -0700454 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700455 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700456 IntentFilter filter = new IntentFilter();
457 filter.addAction(RUN_BACKUP_ACTION);
458 context.registerReceiver(mRunBackupReceiver, filter,
459 android.Manifest.permission.BACKUP, null);
460
461 mRunInitReceiver = new RunInitializeReceiver();
462 filter = new IntentFilter();
463 filter.addAction(RUN_INITIALIZE_ACTION);
464 context.registerReceiver(mRunInitReceiver, filter,
465 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700466
467 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700468 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
469 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
470
Christopher Tate4cc86e12009-09-21 19:36:51 -0700471 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
472 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
473 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
474
Christopher Tatecde87f42009-06-12 12:55:53 -0700475 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700476 mJournalDir = new File(mBaseStateDir, "pending");
477 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700478 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700479
Christopher Tate73e02522009-07-15 14:18:26 -0700480 // Set up the various sorts of package tracking we do
481 initPackageTracking();
482
Christopher Tateabce4e82009-06-18 18:35:32 -0700483 // Build our mapping of uid to backup client services. This implicitly
484 // schedules a backup pass on the Package Manager metadata the first
485 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700486 synchronized (mBackupParticipants) {
487 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700488 }
489
Dan Egnor87a02bc2009-06-17 02:30:10 -0700490 // Set up our transport options and initialize the default transport
491 // TODO: Have transports register themselves somehow?
492 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700493 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700494 ComponentName localName = new ComponentName(context, LocalTransport.class);
495 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700496
Christopher Tate91717492009-06-26 21:07:13 -0700497 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700498 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
499 Settings.Secure.BACKUP_TRANSPORT);
500 if ("".equals(mCurrentTransport)) {
501 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700502 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800503 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700504
505 // Attach to the Google backup transport. When this comes up, it will set
506 // itself as the current transport because we explicitly reset mCurrentTransport
507 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700508 ComponentName transportComponent = new ComponentName("com.google.android.backup",
509 "com.google.android.backup.BackupTransportService");
510 try {
511 // If there's something out there that is supposed to be the Google
512 // backup transport, make sure it's legitimately part of the OS build
513 // and not an app lying about its package name.
514 ApplicationInfo info = mPackageManager.getApplicationInfo(
515 transportComponent.getPackageName(), 0);
516 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
517 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
518 Intent intent = new Intent().setComponent(transportComponent);
519 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
520 } else {
521 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
522 }
523 } catch (PackageManager.NameNotFoundException nnf) {
524 // No such package? No binding.
525 if (DEBUG) Slog.v(TAG, "Google transport not present");
526 }
Christopher Tateaa088442009-06-16 18:25:46 -0700527
Christopher Tatecde87f42009-06-12 12:55:53 -0700528 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700529 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700530 parseLeftoverJournals();
531
Christopher Tateb6787f22009-07-02 17:40:45 -0700532 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700533 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700534
535 // Start the backup passes going
536 setBackupEnabled(areEnabled);
537 }
538
539 private class RunBackupReceiver extends BroadcastReceiver {
540 public void onReceive(Context context, Intent intent) {
541 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700542 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700543 if (mPendingInits.size() > 0) {
544 // If there are pending init operations, we process those
545 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800546 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700547 try {
548 mAlarmManager.cancel(mRunInitIntent);
549 mRunInitIntent.send();
550 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800551 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700552 // can't really do more than bail here
553 }
554 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800555 // Don't run backups now if we're disabled or not yet
556 // fully set up.
557 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800558 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700559
560 // Acquire the wakelock and pass it to the backup thread. it will
561 // be released once backup concludes.
562 mWakelock.acquire();
563
564 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
565 mBackupHandler.sendMessage(msg);
566 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700568 }
569 }
570 }
571 }
572 }
573 }
574
575 private class RunInitializeReceiver extends BroadcastReceiver {
576 public void onReceive(Context context, Intent intent) {
577 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
578 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800579 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700580
581 // Acquire the wakelock and pass it to the init thread. it will
582 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700583 mWakelock.acquire();
584
Christopher Tate4cc86e12009-09-21 19:36:51 -0700585 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700586 mBackupHandler.sendMessage(msg);
587 }
588 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700589 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700590 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700591
Christopher Tate73e02522009-07-15 14:18:26 -0700592 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800593 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700594
Christopher Tate84725812010-02-04 15:52:40 -0800595 // Remember our ancestral dataset
596 mTokenFile = new File(mBaseStateDir, "ancestral");
597 try {
598 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800599 int version = tf.readInt();
600 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
601 mAncestralToken = tf.readLong();
602 mCurrentToken = tf.readLong();
603
604 int numPackages = tf.readInt();
605 if (numPackages >= 0) {
606 mAncestralPackages = new HashSet<String>();
607 for (int i = 0; i < numPackages; i++) {
608 String pkgName = tf.readUTF();
609 mAncestralPackages.add(pkgName);
610 }
611 }
612 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800613 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800614 } catch (FileNotFoundException fnf) {
615 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800616 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800617 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800618 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800619 }
620
Christopher Tatee97e8072009-07-15 16:45:50 -0700621 // Keep a log of what apps we've ever backed up. Because we might have
622 // rebooted in the middle of an operation that was removing something from
623 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700624 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700625 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700626
Christopher Tatee97e8072009-07-15 16:45:50 -0700627 // If we were in the middle of removing something from the ever-backed-up
628 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700629 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700630 if (tempProcessedFile.exists()) {
631 tempProcessedFile.delete();
632 }
633
Dan Egnor852f8e42009-09-30 11:20:45 -0700634 // If there are previous contents, parse them out then start a new
635 // file to continue the recordkeeping.
636 if (mEverStored.exists()) {
637 RandomAccessFile temp = null;
638 RandomAccessFile in = null;
639
640 try {
641 temp = new RandomAccessFile(tempProcessedFile, "rws");
642 in = new RandomAccessFile(mEverStored, "r");
643
644 while (true) {
645 PackageInfo info;
646 String pkg = in.readUTF();
647 try {
648 info = mPackageManager.getPackageInfo(pkg, 0);
649 mEverStoredApps.add(pkg);
650 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800651 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700652 } catch (NameNotFoundException e) {
653 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800654 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700655 }
656 }
657 } catch (EOFException e) {
658 // Once we've rewritten the backup history log, atomically replace the
659 // old one with the new one then reopen the file for continuing use.
660 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800661 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700662 }
663 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800664 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700665 } finally {
666 try { if (temp != null) temp.close(); } catch (IOException e) {}
667 try { if (in != null) in.close(); } catch (IOException e) {}
668 }
669 }
670
Christopher Tate73e02522009-07-15 14:18:26 -0700671 // Register for broadcasts about package install, etc., so we can
672 // update the provider list.
673 IntentFilter filter = new IntentFilter();
674 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
675 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
676 filter.addDataScheme("package");
677 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800678 // Register for events related to sdcard installation.
679 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800680 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
681 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800682 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700683 }
684
Christopher Tatecde87f42009-06-12 12:55:53 -0700685 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700686 for (File f : mJournalDir.listFiles()) {
687 if (mJournal == null || f.compareTo(mJournal) != 0) {
688 // This isn't the current journal, so it must be a leftover. Read
689 // out the package names mentioned there and schedule them for
690 // backup.
691 RandomAccessFile in = null;
692 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400693 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700694 in = new RandomAccessFile(f, "r");
695 while (true) {
696 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400697 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700698 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700699 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700700 } catch (EOFException e) {
701 // no more data; we're done
702 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800703 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700704 } finally {
705 // close/delete the file
706 try { if (in != null) in.close(); } catch (IOException e) {}
707 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700708 }
709 }
710 }
711 }
712
Christopher Tate4cc86e12009-09-21 19:36:51 -0700713 // Maintain persistent state around whether need to do an initialize operation.
714 // Must be called with the queue lock held.
715 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800716 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700717 + " on transport " + transportName);
718 try {
719 IBackupTransport transport = getTransport(transportName);
720 String transportDirName = transport.transportDirName();
721 File stateDir = new File(mBaseStateDir, transportDirName);
722 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
723
724 if (isPending) {
725 // We need an init before we can proceed with sending backup data.
726 // Record that with an entry in our set of pending inits, as well as
727 // journaling it via creation of a sentinel file.
728 mPendingInits.add(transportName);
729 try {
730 (new FileOutputStream(initPendingFile)).close();
731 } catch (IOException ioe) {
732 // Something is badly wrong with our permissions; just try to move on
733 }
734 } else {
735 // No more initialization needed; wipe the journal and reset our state.
736 initPendingFile.delete();
737 mPendingInits.remove(transportName);
738 }
739 } catch (RemoteException e) {
740 // can't happen; the transport is local
741 }
742 }
743
Christopher Tated55e18a2009-09-21 10:12:59 -0700744 // Reset all of our bookkeeping, in response to having been told that
745 // the backend data has been wiped [due to idle expiry, for example],
746 // so we must re-upload all saved settings.
747 void resetBackupState(File stateFileDir) {
748 synchronized (mQueueLock) {
749 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700750 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700751 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700752
Christopher Tate84725812010-02-04 15:52:40 -0800753 mCurrentToken = 0;
754 writeRestoreTokens();
755
Christopher Tated55e18a2009-09-21 10:12:59 -0700756 // Remove all the state files
757 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700758 // ... but don't touch the needs-init sentinel
759 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
760 sf.delete();
761 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700762 }
763
764 // Enqueue a new backup of every participant
765 int N = mBackupParticipants.size();
766 for (int i=0; i<N; i++) {
767 int uid = mBackupParticipants.keyAt(i);
768 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
769 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700770 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700771 }
772 }
773 }
774 }
775
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800776 // Add a transport to our set of available backends. If 'transport' is null, this
777 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700778 private void registerTransport(String name, IBackupTransport transport) {
779 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800780 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800781 if (transport != null) {
782 mTransports.put(name, transport);
783 } else {
784 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800785 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800786 mCurrentTransport = null;
787 }
788 // Nothing further to do in the unregistration case
789 return;
790 }
Christopher Tate91717492009-06-26 21:07:13 -0700791 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700792
793 // If the init sentinel file exists, we need to be sure to perform the init
794 // as soon as practical. We also create the state directory at registration
795 // time to ensure it's present from the outset.
796 try {
797 String transportName = transport.transportDirName();
798 File stateDir = new File(mBaseStateDir, transportName);
799 stateDir.mkdirs();
800
801 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
802 if (initSentinel.exists()) {
803 synchronized (mQueueLock) {
804 mPendingInits.add(transportName);
805
806 // TODO: pick a better starting time than now + 1 minute
807 long delay = 1000 * 60; // one minute, in milliseconds
808 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
809 System.currentTimeMillis() + delay, mRunInitIntent);
810 }
811 }
812 } catch (RemoteException e) {
813 // can't happen, the transport is local
814 }
Christopher Tate91717492009-06-26 21:07:13 -0700815 }
816
Christopher Tate3799bc22009-05-06 16:13:56 -0700817 // ----- Track installation/removal of packages -----
818 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
819 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700821
Christopher Tate3799bc22009-05-06 16:13:56 -0700822 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800823 boolean replacing = false;
824 boolean added = false;
825 Bundle extras = intent.getExtras();
826 String pkgList[] = null;
827 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
828 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
829 Uri uri = intent.getData();
830 if (uri == null) {
831 return;
832 }
833 String pkgName = uri.getSchemeSpecificPart();
834 if (pkgName != null) {
835 pkgList = new String[] { pkgName };
836 }
837 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
838 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800839 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800840 added = true;
841 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800842 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800843 added = false;
844 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
845 }
846 if (pkgList == null || pkgList.length == 0) {
847 return;
848 }
849 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700850 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800851 for (String pkgName : pkgList) {
852 if (replacing) {
853 // The package was just upgraded
854 updatePackageParticipantsLocked(pkgName);
855 } else {
856 // The package was just added
857 addPackageParticipantsLocked(pkgName);
858 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700859 }
860 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800861 } else {
862 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700863 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
864 } else {
865 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800866 for (String pkgName : pkgList) {
867 removePackageParticipantsLocked(pkgName);
868 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700869 }
870 }
871 }
872 }
873 };
874
Dan Egnor87a02bc2009-06-17 02:30:10 -0700875 // ----- Track connection to GoogleBackupTransport service -----
876 ServiceConnection mGoogleConnection = new ServiceConnection() {
877 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800878 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700879 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700880 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700881 }
882
883 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800884 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700885 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700886 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700887 }
888 };
889
Christopher Tate181fafa2009-05-14 11:12:14 -0700890 // Add the backup agents in the given package to our set of known backup participants.
891 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700892 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700893 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800894 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700895 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700896 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700897 }
898
Christopher Tate181fafa2009-05-14 11:12:14 -0700899 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700900 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700901 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800902 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700903 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700905 + " uid=" + p.applicationInfo.uid
906 + " killAfterRestore="
907 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700908 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700909 }
910 }
911
Dan Egnorefe52642009-06-24 00:16:33 -0700912 for (PackageInfo pkg : targetPkgs) {
913 if (packageName == null || pkg.packageName.equals(packageName)) {
914 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700915 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700916 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700917 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700918 mBackupParticipants.put(uid, set);
919 }
Dan Egnorefe52642009-06-24 00:16:33 -0700920 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700921
922 // If we've never seen this app before, schedule a backup for it
923 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800924 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700925 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700926 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700927 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700928 }
Christopher Tate487529a2009-04-29 14:03:25 -0700929 }
930 }
931
Christopher Tate6785dd82009-06-18 15:58:25 -0700932 // Remove the given package's entry from our known active set. If
933 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700934 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800935 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -0800936 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700937 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -0800938 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700939 } else {
940 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -0800941 List<PackageInfo> knownPackages = allAgentPackages();
942 for (PackageInfo pkg : knownPackages) {
943 allApps.add(pkg.packageName);
944 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700945 }
946 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700947 }
948
Joe Onorato8ad02812009-05-13 01:41:44 -0400949 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -0800950 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700951 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800952 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -0800953 + ") removing " + allPackageNames.size() + " entries");
954 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800955 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700956 }
957 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800958 for (String pkg : allPackageNames) {
959 if (packageName == null || pkg.equals(packageName)) {
960 int uid = -1;
961 try {
962 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
963 uid = info.applicationInfo.uid;
964 } catch (NameNotFoundException e) {
965 // we don't know this package name, so just skip it for now
966 continue;
967 }
968
Christopher Tate181fafa2009-05-14 11:12:14 -0700969 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700970 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700971 // Find the existing entry with the same package name, and remove it.
972 // We can't just remove(app) because the instances are different.
973 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -0800974 if (entry.packageName.equals(pkg)) {
975 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700976 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -0800977 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700978 break;
979 }
980 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700981 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700982 mBackupParticipants.delete(uid);
983 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700984 }
985 }
986 }
987 }
988
Christopher Tate181fafa2009-05-14 11:12:14 -0700989 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700990 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700991 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700992 int flags = PackageManager.GET_SIGNATURES;
993 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
994 int N = packages.size();
995 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700996 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700997 try {
998 ApplicationInfo app = pkg.applicationInfo;
999 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001000 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001001 packages.remove(a);
1002 }
1003 else {
1004 // we will need the shared library path, so look that up and store it here
1005 app = mPackageManager.getApplicationInfo(pkg.packageName,
1006 PackageManager.GET_SHARED_LIBRARY_FILES);
1007 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1008 }
1009 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001010 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001011 }
1012 }
Dan Egnorefe52642009-06-24 00:16:33 -07001013 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001014 }
Christopher Tateaa088442009-06-16 18:25:46 -07001015
Christopher Tate3799bc22009-05-06 16:13:56 -07001016 // Reset the given package's known backup participants. Unlike add/remove, the update
1017 // action cannot be passed a null package name.
1018 void updatePackageParticipantsLocked(String packageName) {
1019 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001020 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001021 return;
1022 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001023 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001024
1025 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001026 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001027 List<String> allAppNames = new ArrayList<String>();
1028 for (PackageInfo pkg : allApps) {
1029 allAppNames.add(pkg.packageName);
1030 }
1031 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001033 }
1034
Christopher Tate84725812010-02-04 15:52:40 -08001035 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001036 // backed up at least once
1037 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001038 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1039
1040 synchronized (mEverStoredApps) {
1041 if (!mEverStoredApps.add(packageName)) return;
1042
1043 RandomAccessFile out = null;
1044 try {
1045 out = new RandomAccessFile(mEverStored, "rws");
1046 out.seek(out.length());
1047 out.writeUTF(packageName);
1048 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001049 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001050 } finally {
1051 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001052 }
1053 }
1054 }
1055
Christopher Tatee97e8072009-07-15 16:45:50 -07001056 // Remove our awareness of having ever backed up the given package
1057 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001058 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001059
Dan Egnor852f8e42009-09-30 11:20:45 -07001060 synchronized (mEverStoredApps) {
1061 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1062 // we'll recognize on initialization time that the package no longer
1063 // exists and fix it up then.
1064 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1065 RandomAccessFile known = null;
1066 try {
1067 known = new RandomAccessFile(tempKnownFile, "rws");
1068 mEverStoredApps.remove(packageName);
1069 for (String s : mEverStoredApps) {
1070 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001071 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001072 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001073 known.close();
1074 known = null;
1075 if (!tempKnownFile.renameTo(mEverStored)) {
1076 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1077 }
1078 } catch (IOException e) {
1079 // Bad: we couldn't create the new copy. For safety's sake we
1080 // abandon the whole process and remove all what's-backed-up
1081 // state entirely, meaning we'll force a backup pass for every
1082 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001083 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001084 mEverStoredApps.clear();
1085 tempKnownFile.delete();
1086 mEverStored.delete();
1087 } finally {
1088 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001089 }
1090 }
1091 }
1092
Christopher Tateb49ceb32010-02-08 16:22:24 -08001093 // Persistently record the current and ancestral backup tokens as well
1094 // as the set of packages with data [supposedly] available in the
1095 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001096 void writeRestoreTokens() {
1097 try {
1098 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001099
1100 // First, the version number of this record, for futureproofing
1101 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1102
1103 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001104 af.writeLong(mAncestralToken);
1105 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001106
1107 // Now write the set of ancestral packages
1108 if (mAncestralPackages == null) {
1109 af.writeInt(-1);
1110 } else {
1111 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001112 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001113 for (String pkgName : mAncestralPackages) {
1114 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001115 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001116 }
1117 }
Christopher Tate84725812010-02-04 15:52:40 -08001118 af.close();
1119 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001120 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001121 }
1122 }
1123
Dan Egnor87a02bc2009-06-17 02:30:10 -07001124 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001125 private IBackupTransport getTransport(String transportName) {
1126 synchronized (mTransports) {
1127 IBackupTransport transport = mTransports.get(transportName);
1128 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001129 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001130 }
1131 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001132 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001133 }
1134
Christopher Tatedf01dea2009-06-09 20:45:02 -07001135 // fire off a backup agent, blocking until it attaches or times out
1136 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1137 IBackupAgent agent = null;
1138 synchronized(mAgentConnectLock) {
1139 mConnecting = true;
1140 mConnectedAgent = null;
1141 try {
1142 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001143 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001144
1145 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001146 // only wait 10 seconds for the clear data to happen
1147 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1148 while (mConnecting && mConnectedAgent == null
1149 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001150 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001151 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001152 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001153 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001154 return null;
1155 }
1156 }
1157
1158 // if we timed out with no connect, abort and move on
1159 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001160 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001161 return null;
1162 }
1163 agent = mConnectedAgent;
1164 }
1165 } catch (RemoteException e) {
1166 // can't happen
1167 }
1168 }
1169 return agent;
1170 }
1171
Christopher Tatec7b31e32009-06-10 15:49:30 -07001172 // clear an application's data, blocking until the operation completes or times out
1173 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001174 // Don't wipe packages marked allowClearUserData=false
1175 try {
1176 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1177 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001178 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001179 + packageName);
1180 return;
1181 }
1182 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001183 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001184 return;
1185 }
1186
Christopher Tatec7b31e32009-06-10 15:49:30 -07001187 ClearDataObserver observer = new ClearDataObserver();
1188
1189 synchronized(mClearDataLock) {
1190 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001191 try {
1192 mActivityManager.clearApplicationUserData(packageName, observer);
1193 } catch (RemoteException e) {
1194 // can't happen because the activity manager is in this process
1195 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001196
1197 // only wait 10 seconds for the clear data to happen
1198 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1199 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1200 try {
1201 mClearDataLock.wait(5000);
1202 } catch (InterruptedException e) {
1203 // won't happen, but still.
1204 mClearingData = false;
1205 }
1206 }
1207 }
1208 }
1209
1210 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001211 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001212 synchronized(mClearDataLock) {
1213 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001214 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001215 }
1216 }
1217 }
1218
Christopher Tate1bb69062010-02-19 17:02:12 -08001219 // Get the restore-set token for the best-available restore set for this package:
1220 // the active set if possible, else the ancestral one. Returns zero if none available.
1221 long getAvailableRestoreToken(String packageName) {
1222 long token = mAncestralToken;
1223 synchronized (mQueueLock) {
1224 if (mEverStoredApps.contains(packageName)) {
1225 token = mCurrentToken;
1226 }
1227 }
1228 return token;
1229 }
1230
Christopher Tate44a27902010-01-27 17:15:49 -08001231 // -----
1232 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1233 boolean waitUntilOperationComplete(int token) {
1234 int finalState = OP_PENDING;
1235 synchronized (mCurrentOpLock) {
1236 try {
1237 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1238 try {
1239 mCurrentOpLock.wait();
1240 } catch (InterruptedException e) {}
1241 }
1242 } catch (IndexOutOfBoundsException e) {
1243 // the operation has been mysteriously cleared from our
1244 // bookkeeping -- consider this a success and ignore it.
1245 }
1246 }
1247 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001248 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001249 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001250 return finalState == OP_ACKNOWLEDGED;
1251 }
1252
1253 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001254 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001255 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001256 mCurrentOperations.put(token, OP_PENDING);
1257 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1258 mBackupHandler.sendMessageDelayed(msg, interval);
1259 }
1260
Christopher Tate043dadc2009-06-02 16:11:00 -07001261 // ----- Back up a set of applications via a worker thread -----
1262
Christopher Tate44a27902010-01-27 17:15:49 -08001263 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001264 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001265 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001266 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001267 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001268 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001269
Christopher Tate44a27902010-01-27 17:15:49 -08001270 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001271 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001272 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001273 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001274 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001275
1276 try {
1277 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1278 } catch (RemoteException e) {
1279 // can't happen; the transport is local
1280 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001281 }
1282
Christopher Tate043dadc2009-06-02 16:11:00 -07001283 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001284 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001285 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001286 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001287
Christopher Tate79588342009-06-30 16:11:49 -07001288 // Backups run at background priority
1289 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1290
Christopher Tate043dadc2009-06-02 16:11:00 -07001291 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001292 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001293
Dan Egnor852f8e42009-09-30 11:20:45 -07001294 // If we haven't stored package manager metadata yet, we must init the transport.
1295 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1296 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001297 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001298 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001299 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001300 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001301 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001302 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001303 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001304 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001305 }
Dan Egnor01445162009-09-21 17:04:05 -07001306 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001307
1308 // The package manager doesn't have a proper <application> etc, but since
1309 // it's running here in the system process we can just set up its agent
1310 // directly and use a synthetic BackupRequest. We always run this pass
1311 // because it's cheap and this way we guarantee that we don't get out of
1312 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001313 if (status == BackupConstants.TRANSPORT_OK) {
1314 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1315 mPackageManager, allAgentPackages());
1316 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1317 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1318 status = processOneBackup(pmRequest,
1319 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1320 }
Christopher Tate90967f42009-09-20 15:28:33 -07001321
Dan Egnor01445162009-09-21 17:04:05 -07001322 if (status == BackupConstants.TRANSPORT_OK) {
1323 // Now run all the backups in our queue
1324 status = doQueuedBackups(mTransport);
1325 }
1326
1327 if (status == BackupConstants.TRANSPORT_OK) {
1328 // Tell the transport to finish everything it has buffered
1329 status = mTransport.finishBackup();
1330 if (status == BackupConstants.TRANSPORT_OK) {
1331 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001332 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001333 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001334 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001335 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001336 }
1337 }
1338
Dan Egnor01445162009-09-21 17:04:05 -07001339 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001340 // The backend reports that our dataset has been wiped. We need to
1341 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001342 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001343 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001344 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001345 }
1346 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001347 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001348 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001349 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001350 // If everything actually went through and this is the first time we've
1351 // done a backup, we can now record what the current backup dataset token
1352 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001353 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001354 try {
1355 mCurrentToken = mTransport.getCurrentRestoreSet();
1356 } catch (RemoteException e) { /* cannot happen */ }
1357 writeRestoreTokens();
1358 }
1359
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001360 // If things went wrong, we need to re-stage the apps we had expected
1361 // to be backing up in this pass. This journals the package names in
1362 // the current active pending-backup file, not in the we are holding
1363 // here in mJournal.
1364 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001365 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001366 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001367 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001368 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001369
1370 // We also want to reset the backup schedule based on whatever
1371 // the transport suggests by way of retry/backoff time.
1372 try {
1373 startBackupAlarmsLocked(mTransport.requestBackupTime());
1374 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001375 }
1376
1377 // Either backup was successful, in which case we of course do not need
1378 // this pass's journal any more; or it failed, in which case we just
1379 // re-enqueued all of these packages in the current active journal.
1380 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001381 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001382 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001383 }
1384
Christopher Tatec2af5d32010-02-02 15:18:58 -08001385 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001386 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001387 backupNow();
1388 }
1389
Dan Egnorbb9001c2009-07-27 12:20:13 -07001390 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001391 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001392 }
1393
Dan Egnor01445162009-09-21 17:04:05 -07001394 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001395 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001397
Christopher Tatec28083a2010-12-14 16:16:44 -08001398 // Verify that the requested app exists; it might be something that
1399 // requested a backup but was then uninstalled. The request was
1400 // journalled and rather than tamper with the journal it's safer
1401 // to sanity-check here.
1402 try {
1403 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1404 } catch (NameNotFoundException e) {
1405 Slog.d(TAG, "Package does not exist; skipping");
1406 continue;
1407 }
1408
Christopher Tate043dadc2009-06-02 16:11:00 -07001409 IBackupAgent agent = null;
1410 int mode = (request.fullBackup)
1411 ? IApplicationThread.BACKUP_MODE_FULL
1412 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1413 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001414 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001415 agent = bindToAgentSynchronous(request.appInfo, mode);
1416 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001417 int result = processOneBackup(request, agent, transport);
1418 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001419 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001420 } catch (SecurityException ex) {
1421 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001422 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001423 } finally {
1424 try { // unbind even on timeout, just in case
1425 mActivityManager.unbindBackupAgent(request.appInfo);
1426 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001427 }
1428 }
Dan Egnor01445162009-09-21 17:04:05 -07001429
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001430 mWakelock.setWorkSource(null);
1431
Dan Egnor01445162009-09-21 17:04:05 -07001432 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001433 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001434
Dan Egnor01445162009-09-21 17:04:05 -07001435 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1436 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001437 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001438 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001439
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 File savedStateName = new File(mStateDir, packageName);
1441 File backupDataName = new File(mDataDir, packageName + ".data");
1442 File newStateName = new File(mStateDir, packageName + ".new");
1443
1444 ParcelFileDescriptor savedState = null;
1445 ParcelFileDescriptor backupData = null;
1446 ParcelFileDescriptor newState = null;
1447
1448 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001449 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001450 try {
1451 // Look up the package info & signatures. This is first so that if it
1452 // throws an exception, there's no file setup yet that would need to
1453 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001454 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1455 // The metadata 'package' is synthetic
1456 packInfo = new PackageInfo();
1457 packInfo.packageName = packageName;
1458 } else {
1459 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001460 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001461 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001462
Christopher Tatec7b31e32009-06-10 15:49:30 -07001463 // In a full backup, we pass a null ParcelFileDescriptor as
1464 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001465 if (!request.fullBackup) {
1466 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001467 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001468 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1469 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001470
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 backupData = ParcelFileDescriptor.open(backupDataName,
1472 ParcelFileDescriptor.MODE_READ_WRITE |
1473 ParcelFileDescriptor.MODE_CREATE |
1474 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001475
Dan Egnorbb9001c2009-07-27 12:20:13 -07001476 newState = ParcelFileDescriptor.open(newStateName,
1477 ParcelFileDescriptor.MODE_READ_WRITE |
1478 ParcelFileDescriptor.MODE_CREATE |
1479 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001480
Christopher Tate44a27902010-01-27 17:15:49 -08001481 // Initiate the target's backup pass
1482 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1483 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1484 boolean success = waitUntilOperationComplete(token);
1485
1486 if (!success) {
1487 // timeout -- bail out into the failed-transaction logic
1488 throw new RuntimeException("Backup timeout");
1489 }
1490
Dan Egnorbb9001c2009-07-27 12:20:13 -07001491 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001492 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001493 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001494 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001495 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001496 backupDataName.delete();
1497 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001498 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001499 } finally {
1500 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1501 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1502 try { if (newState != null) newState.close(); } catch (IOException e) {}
1503 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001504 synchronized (mCurrentOpLock) {
1505 mCurrentOperations.clear();
1506 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001507 }
1508
1509 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001510 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001511 try {
1512 int size = (int) backupDataName.length();
1513 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001514 if (result == BackupConstants.TRANSPORT_OK) {
1515 backupData = ParcelFileDescriptor.open(backupDataName,
1516 ParcelFileDescriptor.MODE_READ_ONLY);
1517 result = transport.performBackup(packInfo, backupData);
1518 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001519
Dan Egnor83861e72009-09-17 16:17:55 -07001520 // TODO - We call finishBackup() for each application backed up, because
1521 // we need to know now whether it succeeded or failed. Instead, we should
1522 // hold off on finishBackup() until the end, which implies holding off on
1523 // renaming *all* the output state files (see below) until that happens.
1524
Dan Egnor01445162009-09-21 17:04:05 -07001525 if (result == BackupConstants.TRANSPORT_OK) {
1526 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001527 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001528 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001530 }
1531
1532 // After successful transport, delete the now-stale data
1533 // and juggle the files so that next time we supply the agent
1534 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001535 if (result == BackupConstants.TRANSPORT_OK) {
1536 backupDataName.delete();
1537 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001538 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001539 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001541 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001542 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001543 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001544 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001545 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001546 } finally {
1547 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001548 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001549
Dan Egnor01445162009-09-21 17:04:05 -07001550 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001551 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001552 }
1553
Christopher Tatedf01dea2009-06-09 20:45:02 -07001554
1555 // ----- Restore handling -----
1556
Christopher Tate78dd4a72009-11-04 11:49:08 -08001557 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1558 // If the target resides on the system partition, we allow it to restore
1559 // data from the like-named package in a restore set even if the signatures
1560 // do not match. (Unlike general applications, those flashed to the system
1561 // partition will be signed with the device's platform certificate, so on
1562 // different phones the same system app will have different signatures.)
1563 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001564 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001565 return true;
1566 }
1567
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001568 // Allow unsigned apps, but not signed on one device and unsigned on the other
1569 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001570 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001572 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001573 if ((storedSigs == null || storedSigs.length == 0)
1574 && (deviceSigs == null || deviceSigs.length == 0)) {
1575 return true;
1576 }
1577 if (storedSigs == null || deviceSigs == null) {
1578 return false;
1579 }
1580
Christopher Tateabce4e82009-06-18 18:35:32 -07001581 // !!! TODO: this demands that every stored signature match one
1582 // that is present on device, and does not demand the converse.
1583 // Is this this right policy?
1584 int nStored = storedSigs.length;
1585 int nDevice = deviceSigs.length;
1586
1587 for (int i=0; i < nStored; i++) {
1588 boolean match = false;
1589 for (int j=0; j < nDevice; j++) {
1590 if (storedSigs[i].equals(deviceSigs[j])) {
1591 match = true;
1592 break;
1593 }
1594 }
1595 if (!match) {
1596 return false;
1597 }
1598 }
1599 return true;
1600 }
1601
Christopher Tate44a27902010-01-27 17:15:49 -08001602 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001603 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001604 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001605 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001606 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001607 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001608 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001609 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001610
Christopher Tate5cbbf562009-06-22 16:44:51 -07001611 class RestoreRequest {
1612 public PackageInfo app;
1613 public int storedAppVersion;
1614
1615 RestoreRequest(PackageInfo _app, int _version) {
1616 app = _app;
1617 storedAppVersion = _version;
1618 }
1619 }
1620
Christopher Tate44a27902010-01-27 17:15:49 -08001621 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001622 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1623 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001624 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001625 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001626 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001627 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001628 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001629 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001630
1631 try {
1632 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1633 } catch (RemoteException e) {
1634 // can't happen; the transport is local
1635 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001636 }
1637
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001641 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001642 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001643
Christopher Tateb49ceb32010-02-08 16:22:24 -08001644 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001645 int error = -1; // assume error
1646
Dan Egnorefe52642009-06-24 00:16:33 -07001647 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001648 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001649 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001650 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001651
Dan Egnorefe52642009-06-24 00:16:33 -07001652 // Get the list of all packages which have backup enabled.
1653 // (Include the Package Manager metadata pseudo-package first.)
1654 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1655 PackageInfo omPackage = new PackageInfo();
1656 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1657 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001658
Dan Egnorefe52642009-06-24 00:16:33 -07001659 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001660 if (mTargetPackage == null) {
1661 restorePackages.addAll(agentPackages);
1662 } else {
1663 // Just one package to attempt restore of
1664 restorePackages.add(mTargetPackage);
1665 }
Dan Egnorefe52642009-06-24 00:16:33 -07001666
Christopher Tate7d562ec2009-06-25 18:03:43 -07001667 // let the observer know that we're running
1668 if (mObserver != null) {
1669 try {
1670 // !!! TODO: get an actual count from the transport after
1671 // its startRestore() runs?
1672 mObserver.restoreStarting(restorePackages.size());
1673 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001675 mObserver = null;
1676 }
1677 }
1678
Dan Egnor01445162009-09-21 17:04:05 -07001679 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1680 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001682 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001683 return;
1684 }
1685
1686 String packageName = mTransport.nextRestorePackage();
1687 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001689 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001690 return;
1691 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001692 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001693 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001694 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001695 return;
1696 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001698 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001699 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001700 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001701 return;
1702 }
1703
1704 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001705 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001706 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07001707 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
1708 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07001709
Christopher Tate8c032472009-07-02 14:28:47 -07001710 // Verify that the backup set includes metadata. If not, we can't do
1711 // signature/version verification etc, so we simply do not proceed with
1712 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001713 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001715 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001716 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001717 return;
1718 }
1719
Christopher Tate7d562ec2009-06-25 18:03:43 -07001720 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001721 for (;;) {
1722 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001723
Dan Egnorefe52642009-06-24 00:16:33 -07001724 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001725 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001726 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001727 return;
1728 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001729 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001730 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001731 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001732
Christopher Tate7d562ec2009-06-25 18:03:43 -07001733 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001734 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001735 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001736 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001737 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001738 mObserver = null;
1739 }
1740 }
1741
Dan Egnorefe52642009-06-24 00:16:33 -07001742 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1743 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001744 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001745 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001746 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001747 continue;
1748 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001749
Dan Egnorbb9001c2009-07-27 12:20:13 -07001750 PackageInfo packageInfo;
1751 try {
1752 int flags = PackageManager.GET_SIGNATURES;
1753 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1754 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001755 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001756 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001757 "Package missing on device");
1758 continue;
1759 }
1760
Dan Egnorefe52642009-06-24 00:16:33 -07001761 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001762 // Data is from a "newer" version of the app than we have currently
1763 // installed. If the app has not declared that it is prepared to
1764 // handle this case, we do not attempt the restore.
1765 if ((packageInfo.applicationInfo.flags
1766 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1767 String message = "Version " + metaInfo.versionCode
1768 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001769 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001770 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1771 packageName, message);
1772 continue;
1773 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001774 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001775 + " > installed " + packageInfo.versionCode
1776 + " but restoreAnyVersion");
1777 }
Dan Egnorefe52642009-06-24 00:16:33 -07001778 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001779
Christopher Tate78dd4a72009-11-04 11:49:08 -08001780 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001782 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001783 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001784 continue;
1785 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001786
Joe Onorato8a9b2202010-02-26 18:56:32 -08001787 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001788 + " restore version [" + metaInfo.versionCode
1789 + "] is compatible with installed version ["
1790 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001791
Christopher Tate3de55bc2010-03-12 17:28:08 -08001792 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001793 IBackupAgent agent = bindToAgentSynchronous(
1794 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001795 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001796 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001798 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001799 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001800 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001801 }
1802
Christopher Tate5e1ab332009-09-01 20:32:49 -07001803 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001804 try {
Chris Tate249345b2010-10-29 12:57:04 -07001805 processOneRestore(packageInfo, metaInfo.versionCode, agent,
1806 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001807 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001808 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001809 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001810 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001811
1812 // The agent was probably running with a stub Application object,
1813 // which isn't a valid run mode for the main app logic. Shut
1814 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001815 // usual full initialization. Note that this is only done for
1816 // full-system restores: when a single app has requested a restore,
1817 // it is explicitly not killed following that operation.
1818 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001819 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001820 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001821 + packageInfo.applicationInfo.processName);
1822 mActivityManager.killApplicationProcess(
1823 packageInfo.applicationInfo.processName,
1824 packageInfo.applicationInfo.uid);
1825 }
Dan Egnorefe52642009-06-24 00:16:33 -07001826 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001827 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001828
1829 // if we get this far, report success to the observer
1830 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001831 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001832 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001834 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001835 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001837
Dan Egnorefe52642009-06-24 00:16:33 -07001838 try {
1839 mTransport.finishRestore();
1840 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001842 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001843
1844 if (mObserver != null) {
1845 try {
1846 mObserver.restoreFinished(error);
1847 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001848 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001849 }
1850 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001851
Christopher Tate84725812010-02-04 15:52:40 -08001852 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001853 // ancestral dataset, as well as the set of apps that are possibly
1854 // restoreable from the dataset
1855 if (mTargetPackage == null && pmAgent != null) {
1856 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001857 mAncestralToken = mToken;
1858 writeRestoreTokens();
1859 }
1860
Christopher Tate1bb69062010-02-19 17:02:12 -08001861 // We must under all circumstances tell the Package Manager to
1862 // proceed with install notifications if it's waiting for us.
1863 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001864 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001865 try {
1866 mPackageManagerBinder.finishPackageInstall(mPmToken);
1867 } catch (RemoteException e) { /* can't happen */ }
1868 }
1869
Christopher Tate73a3cb32010-12-13 18:27:26 -08001870 // Furthermore we need to reset the session timeout clock
1871 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
1872 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
1873 TIMEOUT_RESTORE_INTERVAL);
1874
Christopher Tateb6787f22009-07-02 17:40:45 -07001875 // done; we can finally release the wakelock
1876 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001877 }
1878 }
1879
Dan Egnorefe52642009-06-24 00:16:33 -07001880 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07001881 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
1882 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001883 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001884 final String packageName = app.packageName;
1885
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001887
Christopher Tatec7b31e32009-06-10 15:49:30 -07001888 // !!! TODO: get the dirs from the transport
1889 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001890 File newStateName = new File(mStateDir, packageName + ".new");
1891 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001892
Dan Egnorbb9001c2009-07-27 12:20:13 -07001893 ParcelFileDescriptor backupData = null;
1894 ParcelFileDescriptor newState = null;
1895
Christopher Tate44a27902010-01-27 17:15:49 -08001896 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001897 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001898 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001899 backupData = ParcelFileDescriptor.open(backupDataName,
1900 ParcelFileDescriptor.MODE_READ_WRITE |
1901 ParcelFileDescriptor.MODE_CREATE |
1902 ParcelFileDescriptor.MODE_TRUNCATE);
1903
Dan Egnor01445162009-09-21 17:04:05 -07001904 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001905 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001907 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001908 }
1909
1910 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001911 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001912 backupData = ParcelFileDescriptor.open(backupDataName,
1913 ParcelFileDescriptor.MODE_READ_ONLY);
1914
Dan Egnorbb9001c2009-07-27 12:20:13 -07001915 newState = ParcelFileDescriptor.open(newStateName,
1916 ParcelFileDescriptor.MODE_READ_WRITE |
1917 ParcelFileDescriptor.MODE_CREATE |
1918 ParcelFileDescriptor.MODE_TRUNCATE);
1919
Christopher Tate44a27902010-01-27 17:15:49 -08001920 // Kick off the restore, checking for hung agents
1921 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1922 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1923 boolean success = waitUntilOperationComplete(token);
1924
1925 if (!success) {
1926 throw new RuntimeException("restore timeout");
1927 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001928
1929 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001930 //
1931 // !!! TODO: the restored data should be migrated on the server
1932 // side into the current dataset. In that case the new state file
1933 // we just created would reflect the data already extant in the
1934 // backend, so there'd be nothing more to do. Until that happens,
1935 // however, we need to make sure that we record the data to the
1936 // current backend dataset. (Yes, this means shipping the data over
1937 // the wire in both directions. That's bad, but consistency comes
1938 // first, then efficiency.) Once we introduce server-side data
1939 // migration to the newly-restored device's dataset, we will change
1940 // the following from a discard of the newly-written state to the
1941 // "correct" operation of renaming into the canonical state blob.
1942 newStateName.delete(); // TODO: remove; see above comment
1943 //newStateName.renameTo(savedStateName); // TODO: replace with this
1944
Dan Egnorbb9001c2009-07-27 12:20:13 -07001945 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001946 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001947 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001948 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001950
Christopher Tate96733042009-07-20 14:49:13 -07001951 // If the agent fails restore, it might have put the app's data
1952 // into an incoherent state. For consistency we wipe its data
1953 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001954 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001955 } finally {
1956 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001957 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1958 try { if (newState != null) newState.close(); } catch (IOException e) {}
1959 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001960 mCurrentOperations.delete(token);
Chris Tate249345b2010-10-29 12:57:04 -07001961
1962 // If we know a priori that we'll need to perform a full post-restore backup
1963 // pass, clear the new state file data. This means we're discarding work that
1964 // was just done by the app's agent, but this way the agent doesn't need to
1965 // take any special action based on global device state.
1966 if (needFullBackup) {
1967 newStateName.delete();
1968 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001969 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001970 }
1971 }
1972
Christopher Tate44a27902010-01-27 17:15:49 -08001973 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001974 IBackupTransport mTransport;
1975 PackageInfo mPackage;
1976
Christopher Tate44a27902010-01-27 17:15:49 -08001977 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001978 mTransport = transport;
1979 mPackage = packageInfo;
1980 }
1981
Christopher Tateee0e78a2009-07-02 11:17:03 -07001982 public void run() {
1983 try {
1984 // Clear the on-device backup state to ensure a full backup next time
1985 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1986 File stateFile = new File(stateDir, mPackage.packageName);
1987 stateFile.delete();
1988
1989 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001990 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001991 mTransport.clearBackupData(mPackage);
1992 } catch (RemoteException e) {
1993 // can't happen; the transport is local
1994 } finally {
1995 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001996 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001997 mTransport.finishBackup();
1998 } catch (RemoteException e) {
1999 // can't happen; the transport is local
2000 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002001
2002 // Last but not least, release the cpu
2003 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002004 }
2005 }
2006 }
2007
Christopher Tate44a27902010-01-27 17:15:49 -08002008 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002009 HashSet<String> mQueue;
2010
Christopher Tate44a27902010-01-27 17:15:49 -08002011 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002012 mQueue = transportNames;
2013 }
2014
Christopher Tate4cc86e12009-09-21 19:36:51 -07002015 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002016 try {
2017 for (String transportName : mQueue) {
2018 IBackupTransport transport = getTransport(transportName);
2019 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002020 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002021 continue;
2022 }
2023
Joe Onorato8a9b2202010-02-26 18:56:32 -08002024 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002025 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002026 long startRealtime = SystemClock.elapsedRealtime();
2027 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002028
Christopher Tate4cc86e12009-09-21 19:36:51 -07002029 if (status == BackupConstants.TRANSPORT_OK) {
2030 status = transport.finishBackup();
2031 }
2032
2033 // Okay, the wipe really happened. Clean up our local bookkeeping.
2034 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002035 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002036 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002037 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002038 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002039 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002040 synchronized (mQueueLock) {
2041 recordInitPendingLocked(false, transportName);
2042 }
Dan Egnor726247c2009-09-29 19:12:31 -07002043 } else {
2044 // If this didn't work, requeue this one and try again
2045 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002047 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002048 synchronized (mQueueLock) {
2049 recordInitPendingLocked(true, transportName);
2050 }
2051 // do this via another alarm to make sure of the wakelock states
2052 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002053 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002054 + transportName + " resched in " + delay);
2055 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2056 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002057 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002058 }
2059 } catch (RemoteException e) {
2060 // can't happen; the transports are local
2061 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002062 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002063 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002064 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002065 mWakelock.release();
2066 }
2067 }
2068 }
2069
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002070 private void dataChangedImpl(String packageName) {
2071 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2072 dataChangedImpl(packageName, targets);
2073 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002074
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002075 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002076 // Record that we need a backup pass for the caller. Since multiple callers
2077 // may share a uid, we need to note all candidates within that uid and schedule
2078 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002079 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002080
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002081 if (targets == null) {
2082 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2083 + " uid=" + Binder.getCallingUid());
2084 return;
2085 }
2086
2087 synchronized (mQueueLock) {
2088 // Note that this client has made data changes that need to be backed up
2089 for (ApplicationInfo app : targets) {
2090 // validate the caller-supplied package name against the known set of
2091 // packages associated with this uid
2092 if (app.packageName.equals(packageName)) {
2093 // Add the caller to the set of pending backups. If there is
2094 // one already there, then overwrite it, but no harm done.
2095 BackupRequest req = new BackupRequest(app, false);
Christopher Tatec28083a2010-12-14 16:16:44 -08002096 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002097 // Journal this request in case of crash. The put()
2098 // operation returned null when this package was not already
2099 // in the set; we want to avoid touching the disk redundantly.
2100 writeToJournalLocked(packageName);
2101
2102 if (DEBUG) {
2103 int numKeys = mPendingBackups.size();
2104 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2105 for (BackupRequest b : mPendingBackups.values()) {
2106 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2107 }
2108 }
2109 }
2110 }
2111 }
2112 }
2113 }
2114
2115 // Note: packageName is currently unused, but may be in the future
2116 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002117 // If the caller does not hold the BACKUP permission, it can only request a
2118 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002119 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002120 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002121 synchronized (mBackupParticipants) {
2122 return mBackupParticipants.get(Binder.getCallingUid());
2123 }
2124 }
2125
2126 // a caller with full permission can ask to back up any participating app
2127 // !!! TODO: allow backup of ANY app?
2128 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2129 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002130 int N = mBackupParticipants.size();
2131 for (int i = 0; i < N; i++) {
2132 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2133 if (s != null) {
2134 targets.addAll(s);
2135 }
2136 }
2137 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002138 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002139 }
Christopher Tate46758122009-05-06 11:22:00 -07002140
Christopher Tatecde87f42009-06-12 12:55:53 -07002141 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002142 RandomAccessFile out = null;
2143 try {
2144 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2145 out = new RandomAccessFile(mJournal, "rws");
2146 out.seek(out.length());
2147 out.writeUTF(str);
2148 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002149 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002150 mJournal = null;
2151 } finally {
2152 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002153 }
2154 }
2155
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002156 // ----- IBackupManager binder interface -----
2157
2158 public void dataChanged(final String packageName) {
2159 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2160 if (targets == null) {
2161 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2162 + " uid=" + Binder.getCallingUid());
2163 return;
2164 }
2165
2166 mBackupHandler.post(new Runnable() {
2167 public void run() {
2168 dataChangedImpl(packageName, targets);
2169 }
2170 });
2171 }
2172
Christopher Tateee0e78a2009-07-02 11:17:03 -07002173 // Clear the given package's backup data from the current transport
2174 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002175 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002176 PackageInfo info;
2177 try {
2178 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2179 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002180 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002181 return;
2182 }
2183
2184 // If the caller does not hold the BACKUP permission, it can only request a
2185 // wipe of its own backed-up data.
2186 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002187 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002188 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2189 apps = mBackupParticipants.get(Binder.getCallingUid());
2190 } else {
2191 // a caller with full permission can ask to back up any participating app
2192 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002193 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002194 apps = new HashSet<ApplicationInfo>();
2195 int N = mBackupParticipants.size();
2196 for (int i = 0; i < N; i++) {
2197 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2198 if (s != null) {
2199 apps.addAll(s);
2200 }
2201 }
2202 }
2203
2204 // now find the given package in the set of candidate apps
2205 for (ApplicationInfo app : apps) {
2206 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002207 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002208 // found it; fire off the clear request
2209 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002210 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002211 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002212 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2213 new ClearParams(getTransport(mCurrentTransport), info));
2214 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002215 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002216 }
2217 break;
2218 }
2219 }
2220 }
2221
Christopher Tateace7f092009-06-15 18:07:25 -07002222 // Run a backup pass immediately for any applications that have declared
2223 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002224 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002225 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002226
Joe Onorato8a9b2202010-02-26 18:56:32 -08002227 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002228 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002229 // Because the alarms we are using can jitter, and we want an *immediate*
2230 // backup pass to happen, we restart the timer beginning with "next time,"
2231 // then manually fire the backup trigger intent ourselves.
2232 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002233 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002234 mRunBackupIntent.send();
2235 } catch (PendingIntent.CanceledException e) {
2236 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002238 }
Christopher Tate46758122009-05-06 11:22:00 -07002239 }
2240 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002241
Christopher Tate8031a3d2009-07-06 16:36:05 -07002242 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002243 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002244 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2245 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002246
Joe Onorato8a9b2202010-02-26 18:56:32 -08002247 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002248
Christopher Tate6ef58a12009-06-29 14:56:28 -07002249 boolean wasEnabled = mEnabled;
2250 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002251 Settings.Secure.putInt(mContext.getContentResolver(),
2252 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002253 mEnabled = enable;
2254 }
2255
Christopher Tate49401dd2009-07-01 12:34:29 -07002256 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002257 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002258 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002259 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002260 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002261 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002262 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002263
Christopher Tateb6787f22009-07-02 17:40:45 -07002264 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002265
2266 // This also constitutes an opt-out, so we wipe any data for
2267 // this device from the backend. We start that process with
2268 // an alarm in order to guarantee wakelock states.
2269 if (wasEnabled && mProvisioned) {
2270 // NOTE: we currently flush every registered transport, not just
2271 // the currently-active one.
2272 HashSet<String> allTransports;
2273 synchronized (mTransports) {
2274 allTransports = new HashSet<String>(mTransports.keySet());
2275 }
2276 // build the set of transports for which we are posting an init
2277 for (String transport : allTransports) {
2278 recordInitPendingLocked(true, transport);
2279 }
2280 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2281 mRunInitIntent);
2282 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002283 }
2284 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002285 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002286
Christopher Tatecce9da52010-02-03 15:11:15 -08002287 // Enable/disable automatic restore of app data at install time
2288 public void setAutoRestore(boolean doAutoRestore) {
2289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2290 "setBackupEnabled");
2291
Joe Onorato8a9b2202010-02-26 18:56:32 -08002292 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002293
2294 synchronized (this) {
2295 Settings.Secure.putInt(mContext.getContentResolver(),
2296 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2297 mAutoRestore = doAutoRestore;
2298 }
2299 }
2300
Christopher Tate8031a3d2009-07-06 16:36:05 -07002301 // Mark the backup service as having been provisioned
2302 public void setBackupProvisioned(boolean available) {
2303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2304 "setBackupProvisioned");
2305
2306 boolean wasProvisioned = mProvisioned;
2307 synchronized (this) {
2308 Settings.Secure.putInt(mContext.getContentResolver(),
2309 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2310 mProvisioned = available;
2311 }
2312
2313 synchronized (mQueueLock) {
2314 if (available && !wasProvisioned && mEnabled) {
2315 // we're now good to go, so start the backup alarms
2316 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2317 } else if (!available) {
2318 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002319 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002320 mAlarmManager.cancel(mRunBackupIntent);
2321 }
2322 }
2323 }
2324
2325 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002326 // We used to use setInexactRepeating(), but that may be linked to
2327 // backups running at :00 more often than not, creating load spikes.
2328 // Schedule at an exact time for now, and also add a bit of "fuzz".
2329
2330 Random random = new Random();
2331 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2332 random.nextInt(FUZZ_MILLIS);
2333 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2334 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002335 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002336 }
2337
Christopher Tate6ef58a12009-06-29 14:56:28 -07002338 // Report whether the backup mechanism is currently enabled
2339 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002341 return mEnabled; // no need to synchronize just to read it
2342 }
2343
Christopher Tate91717492009-06-26 21:07:13 -07002344 // Report the name of the currently active transport
2345 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002347 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002348 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002349 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002350 }
2351
Christopher Tate91717492009-06-26 21:07:13 -07002352 // Report all known, available backup transports
2353 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002355
Christopher Tate91717492009-06-26 21:07:13 -07002356 String[] list = null;
2357 ArrayList<String> known = new ArrayList<String>();
2358 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2359 if (entry.getValue() != null) {
2360 known.add(entry.getKey());
2361 }
2362 }
2363
2364 if (known.size() > 0) {
2365 list = new String[known.size()];
2366 known.toArray(list);
2367 }
2368 return list;
2369 }
2370
2371 // Select which transport to use for the next backup operation. If the given
2372 // name is not one of the available transports, no action is taken and the method
2373 // returns null.
2374 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002375 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002376
2377 synchronized (mTransports) {
2378 String prevTransport = null;
2379 if (mTransports.get(transport) != null) {
2380 prevTransport = mCurrentTransport;
2381 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002382 Settings.Secure.putString(mContext.getContentResolver(),
2383 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002384 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002385 + " returning " + prevTransport);
2386 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002387 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002388 }
2389 return prevTransport;
2390 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002391 }
2392
Christopher Tatef5e1c292010-12-08 18:40:26 -08002393 // Supply the configuration Intent for the given transport. If the name is not one
2394 // of the available transports, or if the transport does not supply any configuration
2395 // UI, the method returns null.
2396 public Intent getConfigurationIntent(String transportName) {
2397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2398 "getConfigurationIntent");
2399
2400 synchronized (mTransports) {
2401 final IBackupTransport transport = mTransports.get(transportName);
2402 if (transport != null) {
2403 try {
2404 final Intent intent = transport.configurationIntent();
2405 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2406 + intent);
2407 return intent;
2408 } catch (RemoteException e) {
2409 /* fall through to return null */
2410 }
2411 }
2412 }
2413
2414 return null;
2415 }
2416
2417 // Supply the configuration summary string for the given transport. If the name is
2418 // not one of the available transports, or if the transport does not supply any
2419 // summary / destination string, the method can return null.
2420 //
2421 // This string is used VERBATIM as the summary text of the relevant Settings item!
2422 public String getDestinationString(String transportName) {
2423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2424 "getConfigurationIntent");
2425
2426 synchronized (mTransports) {
2427 final IBackupTransport transport = mTransports.get(transportName);
2428 if (transport != null) {
2429 try {
2430 final String text = transport.currentDestinationString();
2431 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2432 return text;
2433 } catch (RemoteException e) {
2434 /* fall through to return null */
2435 }
2436 }
2437 }
2438
2439 return null;
2440 }
2441
Christopher Tate043dadc2009-06-02 16:11:00 -07002442 // Callback: a requested backup agent has been instantiated. This should only
2443 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002444 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002445 synchronized(mAgentConnectLock) {
2446 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002447 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002448 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2449 mConnectedAgent = agent;
2450 mConnecting = false;
2451 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002452 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002453 + " claiming agent connected");
2454 }
2455 mAgentConnectLock.notifyAll();
2456 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002457 }
2458
2459 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2460 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002461 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002462 public void agentDisconnected(String packageName) {
2463 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002464 synchronized(mAgentConnectLock) {
2465 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2466 mConnectedAgent = null;
2467 mConnecting = false;
2468 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002470 + " claiming agent disconnected");
2471 }
2472 mAgentConnectLock.notifyAll();
2473 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002474 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002475
Christopher Tate1bb69062010-02-19 17:02:12 -08002476 // An application being installed will need a restore pass, then the Package Manager
2477 // will need to be told when the restore is finished.
2478 public void restoreAtInstall(String packageName, int token) {
2479 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002480 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002481 + " attemping install-time restore");
2482 return;
2483 }
2484
2485 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002486 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002487 + " token=" + Integer.toHexString(token));
2488
Christopher Tatef0872722010-02-25 15:22:48 -08002489 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002490 // okay, we're going to attempt a restore of this package from this restore set.
2491 // The eventual message back into the Package Manager to run the post-install
2492 // steps for 'token' will be issued from the restore handling code.
2493
2494 // We can use a synthetic PackageInfo here because:
2495 // 1. We know it's valid, since the Package Manager supplied the name
2496 // 2. Only the packageName field will be used by the restore code
2497 PackageInfo pkg = new PackageInfo();
2498 pkg.packageName = packageName;
2499
2500 mWakelock.acquire();
2501 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2502 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002503 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002504 mBackupHandler.sendMessage(msg);
2505 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002506 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2507 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002508 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002509 try {
2510 mPackageManagerBinder.finishPackageInstall(token);
2511 } catch (RemoteException e) { /* can't happen */ }
2512 }
2513 }
2514
Christopher Tate8c850b72009-06-07 19:33:20 -07002515 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002516 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2517 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2518 + " transport=" + transport);
2519
2520 boolean needPermission = true;
2521 if (transport == null) {
2522 transport = mCurrentTransport;
2523
2524 if (packageName != null) {
2525 PackageInfo app = null;
2526 try {
2527 app = mPackageManager.getPackageInfo(packageName, 0);
2528 } catch (NameNotFoundException nnf) {
2529 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2530 throw new IllegalArgumentException("Package " + packageName + " not found");
2531 }
2532
2533 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2534 // So: using the current active transport, and the caller has asked
2535 // that its own package will be restored. In this narrow use case
2536 // we do not require the caller to hold the permission.
2537 needPermission = false;
2538 }
2539 }
2540 }
2541
2542 if (needPermission) {
2543 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2544 "beginRestoreSession");
2545 } else {
2546 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2547 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002548
2549 synchronized(this) {
2550 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002551 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002552 return null;
2553 }
Chris Tate44ab8452010-11-16 15:10:49 -08002554 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08002555 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07002556 }
2557 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002558 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002559
Christopher Tate73a3cb32010-12-13 18:27:26 -08002560 void clearRestoreSession(ActiveRestoreSession currentSession) {
2561 synchronized(this) {
2562 if (currentSession != mActiveRestoreSession) {
2563 Slog.e(TAG, "ending non-current restore session");
2564 } else {
2565 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
2566 mActiveRestoreSession = null;
2567 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2568 }
2569 }
2570 }
2571
Christopher Tate44a27902010-01-27 17:15:49 -08002572 // Note that a currently-active backup agent has notified us that it has
2573 // completed the given outstanding asynchronous backup/restore operation.
2574 public void opComplete(int token) {
2575 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002576 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002577 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2578 mCurrentOpLock.notifyAll();
2579 }
2580 }
2581
Christopher Tate9b3905c2009-06-08 15:24:01 -07002582 // ----- Restore session -----
2583
Christopher Tate80202c82010-01-25 19:37:47 -08002584 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002585 private static final String TAG = "RestoreSession";
2586
Chris Tate44ab8452010-11-16 15:10:49 -08002587 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002588 private IBackupTransport mRestoreTransport = null;
2589 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08002590 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002591
Chris Tate44ab8452010-11-16 15:10:49 -08002592 ActiveRestoreSession(String packageName, String transport) {
2593 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07002594 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002595 }
2596
2597 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002598 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002599 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002600 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002601 if (observer == null) {
2602 throw new IllegalArgumentException("Observer must not be null");
2603 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002604
Christopher Tate73a3cb32010-12-13 18:27:26 -08002605 if (mEnded) {
2606 throw new IllegalStateException("Restore session already ended");
2607 }
2608
Christopher Tate1bb69062010-02-19 17:02:12 -08002609 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002610 try {
Christopher Tate43383042009-07-13 15:17:13 -07002611 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002612 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002613 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002614 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002615 // spin off the transport request to our service thread
2616 mWakelock.acquire();
2617 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2618 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2619 mBackupHandler.sendMessage(msg);
2620 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002621 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002622 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002623 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002624 } finally {
2625 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002626 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002627 }
2628
Christopher Tate84725812010-02-04 15:52:40 -08002629 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002630 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2631 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002632
Chris Tate44ab8452010-11-16 15:10:49 -08002633 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002634 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002635
Christopher Tate73a3cb32010-12-13 18:27:26 -08002636 if (mEnded) {
2637 throw new IllegalStateException("Restore session already ended");
2638 }
2639
Dan Egnor0084da52009-07-29 12:57:16 -07002640 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08002641 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
2642 return -1;
2643 }
2644
2645 if (mPackageName != null) {
2646 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07002647 return -1;
2648 }
2649
Christopher Tate21ab6a52009-09-24 18:01:46 -07002650 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002651 for (int i = 0; i < mRestoreSets.length; i++) {
2652 if (token == mRestoreSets[i].token) {
2653 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002654 mWakelock.acquire();
2655 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002656 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07002657 mBackupHandler.sendMessage(msg);
2658 Binder.restoreCallingIdentity(oldId);
2659 return 0;
2660 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002661 }
2662 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002663
Joe Onorato8a9b2202010-02-26 18:56:32 -08002664 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002665 return -1;
2666 }
2667
Christopher Tate84725812010-02-04 15:52:40 -08002668 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002669 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002670
Christopher Tate73a3cb32010-12-13 18:27:26 -08002671 if (mEnded) {
2672 throw new IllegalStateException("Restore session already ended");
2673 }
2674
Chris Tate44ab8452010-11-16 15:10:49 -08002675 if (mPackageName != null) {
2676 if (! mPackageName.equals(packageName)) {
2677 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
2678 + " on session for package " + mPackageName);
2679 return -1;
2680 }
2681 }
2682
Christopher Tate84725812010-02-04 15:52:40 -08002683 PackageInfo app = null;
2684 try {
2685 app = mPackageManager.getPackageInfo(packageName, 0);
2686 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002687 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002688 return -1;
2689 }
2690
2691 // If the caller is not privileged and is not coming from the target
2692 // app's uid, throw a permission exception back to the caller.
2693 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2694 Binder.getCallingPid(), Binder.getCallingUid());
2695 if ((perm == PackageManager.PERMISSION_DENIED) &&
2696 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002697 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002698 + " or calling uid=" + Binder.getCallingUid());
2699 throw new SecurityException("No permission to restore other packages");
2700 }
2701
Christopher Tate7d411a32010-02-26 11:27:08 -08002702 // If the package has no backup agent, we obviously cannot proceed
2703 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002704 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002705 return -1;
2706 }
2707
Christopher Tate84725812010-02-04 15:52:40 -08002708 // So far so good; we're allowed to try to restore this package. Now
2709 // check whether there is data for it in the current dataset, falling back
2710 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002711 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002712
2713 // If we didn't come up with a place to look -- no ancestral dataset and
2714 // the app has never been backed up from this device -- there's nothing
2715 // to do but return failure.
2716 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08002717 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08002718 return -1;
2719 }
2720
2721 // Ready to go: enqueue the restore request and claim success
2722 long oldId = Binder.clearCallingIdentity();
2723 mWakelock.acquire();
2724 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002725 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08002726 mBackupHandler.sendMessage(msg);
2727 Binder.restoreCallingIdentity(oldId);
2728 return 0;
2729 }
2730
Christopher Tate73a3cb32010-12-13 18:27:26 -08002731 // Posted to the handler to tear down a restore session in a cleanly synchronized way
2732 class EndRestoreRunnable implements Runnable {
2733 BackupManagerService mBackupManager;
2734 ActiveRestoreSession mSession;
2735
2736 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
2737 mBackupManager = manager;
2738 mSession = session;
2739 }
2740
2741 public void run() {
2742 // clean up the session's bookkeeping
2743 synchronized (mSession) {
2744 try {
2745 if (mSession.mRestoreTransport != null) {
2746 mSession.mRestoreTransport.finishRestore();
2747 }
2748 } catch (Exception e) {
2749 Slog.e(TAG, "Error in finishRestore", e);
2750 } finally {
2751 mSession.mRestoreTransport = null;
2752 mSession.mEnded = true;
2753 }
2754 }
2755
2756 // clean up the BackupManagerService side of the bookkeeping
2757 // and cancel any pending timeout message
2758 mBackupManager.clearRestoreSession(mSession);
2759 }
2760 }
2761
Dan Egnor0084da52009-07-29 12:57:16 -07002762 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002763 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002764
Christopher Tate73a3cb32010-12-13 18:27:26 -08002765 if (mEnded) {
2766 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07002767 }
2768
Christopher Tate73a3cb32010-12-13 18:27:26 -08002769 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07002770 }
2771 }
2772
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002773 @Override
2774 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002775 long identityToken = Binder.clearCallingIdentity();
2776 try {
2777 dumpInternal(pw);
2778 } finally {
2779 Binder.restoreCallingIdentity(identityToken);
2780 }
2781 }
2782
2783 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002784 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002785 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002786 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002787 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002788 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002789 pw.println("Last backup pass: " + mLastBackupPass
2790 + " (now = " + System.currentTimeMillis() + ')');
2791 pw.println(" next scheduled: " + mNextBackupPass);
2792
Christopher Tate91717492009-06-26 21:07:13 -07002793 pw.println("Available transports:");
2794 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002795 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2796 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002797 IBackupTransport transport = getTransport(t);
2798 File dir = new File(mBaseStateDir, transport.transportDirName());
2799 pw.println(" destination: " + transport.currentDestinationString());
2800 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07002801 for (File f : dir.listFiles()) {
2802 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2803 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002804 } catch (Exception e) {
2805 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002806 pw.println(" Error: " + e);
2807 }
Christopher Tate91717492009-06-26 21:07:13 -07002808 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002809
2810 pw.println("Pending init: " + mPendingInits.size());
2811 for (String s : mPendingInits) {
2812 pw.println(" " + s);
2813 }
2814
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002815 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002816 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002817 for (int i=0; i<N; i++) {
2818 int uid = mBackupParticipants.keyAt(i);
2819 pw.print(" uid: ");
2820 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002821 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2822 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002823 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002824 }
2825 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002826
Christopher Tateb49ceb32010-02-08 16:22:24 -08002827 pw.println("Ancestral packages: "
2828 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002829 if (mAncestralPackages != null) {
2830 for (String pkg : mAncestralPackages) {
2831 pw.println(" " + pkg);
2832 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002833 }
2834
Christopher Tate73e02522009-07-15 14:18:26 -07002835 pw.println("Ever backed up: " + mEverStoredApps.size());
2836 for (String pkg : mEverStoredApps) {
2837 pw.println(" " + pkg);
2838 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002839
2840 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002841 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002842 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002843 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002844 }
2845 }
Christopher Tate487529a2009-04-29 14:03:25 -07002846}