blob: c48f3605b2b452040dbe37b00a34b270fbd9b610 [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
382 mWakelock.release();
383 }
384 break;
385 }
386
Christopher Tate44a27902010-01-27 17:15:49 -0800387 case MSG_TIMEOUT:
388 {
389 synchronized (mCurrentOpLock) {
390 final int token = msg.arg1;
391 int state = mCurrentOperations.get(token, OP_TIMEOUT);
392 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800393 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800394 mCurrentOperations.put(token, OP_TIMEOUT);
395 }
396 mCurrentOpLock.notifyAll();
397 }
398 break;
399 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800400
401 case MSG_RESTORE_TIMEOUT:
402 {
403 synchronized (BackupManagerService.this) {
404 if (mActiveRestoreSession != null) {
405 // Client app left the restore session dangling. We know that it
406 // can't be in the middle of an actual restore operation because
407 // those are executed serially on this same handler thread. Clean
408 // up now.
409 Slog.w(TAG, "Restore session timed out; aborting");
410 post(mActiveRestoreSession.new EndRestoreRunnable(
411 BackupManagerService.this, mActiveRestoreSession));
412 }
413 }
414 }
Christopher Tate44a27902010-01-27 17:15:49 -0800415 }
416 }
417 }
418
419 // ----- Main service implementation -----
420
Christopher Tate487529a2009-04-29 14:03:25 -0700421 public BackupManagerService(Context context) {
422 mContext = context;
423 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700424 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700425 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700426
Christopher Tateb6787f22009-07-02 17:40:45 -0700427 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
428 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
429
Christopher Tate44a27902010-01-27 17:15:49 -0800430 mBackupManagerBinder = asInterface(asBinder());
431
432 // spin up the backup/restore handler thread
433 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
434 mHandlerThread.start();
435 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
436
Christopher Tate22b87872009-05-04 16:41:53 -0700437 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700438 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700439 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700440 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700441 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800442 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800443 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800444 // If Encrypted file systems is enabled or disabled, this call will return the
445 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600446 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800447 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700448 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700449
Christopher Tate4cc86e12009-09-21 19:36:51 -0700450 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700451 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700452 IntentFilter filter = new IntentFilter();
453 filter.addAction(RUN_BACKUP_ACTION);
454 context.registerReceiver(mRunBackupReceiver, filter,
455 android.Manifest.permission.BACKUP, null);
456
457 mRunInitReceiver = new RunInitializeReceiver();
458 filter = new IntentFilter();
459 filter.addAction(RUN_INITIALIZE_ACTION);
460 context.registerReceiver(mRunInitReceiver, filter,
461 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700462
463 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700464 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
465 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
466
Christopher Tate4cc86e12009-09-21 19:36:51 -0700467 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
468 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
469 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
470
Christopher Tatecde87f42009-06-12 12:55:53 -0700471 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700472 mJournalDir = new File(mBaseStateDir, "pending");
473 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700474 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700475
Christopher Tate73e02522009-07-15 14:18:26 -0700476 // Set up the various sorts of package tracking we do
477 initPackageTracking();
478
Christopher Tateabce4e82009-06-18 18:35:32 -0700479 // Build our mapping of uid to backup client services. This implicitly
480 // schedules a backup pass on the Package Manager metadata the first
481 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700482 synchronized (mBackupParticipants) {
483 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700484 }
485
Dan Egnor87a02bc2009-06-17 02:30:10 -0700486 // Set up our transport options and initialize the default transport
487 // TODO: Have transports register themselves somehow?
488 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700489 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700490 ComponentName localName = new ComponentName(context, LocalTransport.class);
491 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700492
Christopher Tate91717492009-06-26 21:07:13 -0700493 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700494 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
495 Settings.Secure.BACKUP_TRANSPORT);
496 if ("".equals(mCurrentTransport)) {
497 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700498 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800499 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700500
501 // Attach to the Google backup transport. When this comes up, it will set
502 // itself as the current transport because we explicitly reset mCurrentTransport
503 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700504 ComponentName transportComponent = new ComponentName("com.google.android.backup",
505 "com.google.android.backup.BackupTransportService");
506 try {
507 // If there's something out there that is supposed to be the Google
508 // backup transport, make sure it's legitimately part of the OS build
509 // and not an app lying about its package name.
510 ApplicationInfo info = mPackageManager.getApplicationInfo(
511 transportComponent.getPackageName(), 0);
512 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
513 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
514 Intent intent = new Intent().setComponent(transportComponent);
515 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
516 } else {
517 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
518 }
519 } catch (PackageManager.NameNotFoundException nnf) {
520 // No such package? No binding.
521 if (DEBUG) Slog.v(TAG, "Google transport not present");
522 }
Christopher Tateaa088442009-06-16 18:25:46 -0700523
Christopher Tatecde87f42009-06-12 12:55:53 -0700524 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700525 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700526 parseLeftoverJournals();
527
Christopher Tateb6787f22009-07-02 17:40:45 -0700528 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700529 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700530
531 // Start the backup passes going
532 setBackupEnabled(areEnabled);
533 }
534
535 private class RunBackupReceiver extends BroadcastReceiver {
536 public void onReceive(Context context, Intent intent) {
537 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700538 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700539 if (mPendingInits.size() > 0) {
540 // If there are pending init operations, we process those
541 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800542 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700543 try {
544 mAlarmManager.cancel(mRunInitIntent);
545 mRunInitIntent.send();
546 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800547 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700548 // can't really do more than bail here
549 }
550 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800551 // Don't run backups now if we're disabled or not yet
552 // fully set up.
553 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800554 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700555
556 // Acquire the wakelock and pass it to the backup thread. it will
557 // be released once backup concludes.
558 mWakelock.acquire();
559
560 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
561 mBackupHandler.sendMessage(msg);
562 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800563 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700564 }
565 }
566 }
567 }
568 }
569 }
570
571 private class RunInitializeReceiver extends BroadcastReceiver {
572 public void onReceive(Context context, Intent intent) {
573 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
574 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800575 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700576
577 // Acquire the wakelock and pass it to the init thread. it will
578 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700579 mWakelock.acquire();
580
Christopher Tate4cc86e12009-09-21 19:36:51 -0700581 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700582 mBackupHandler.sendMessage(msg);
583 }
584 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700585 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700586 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700587
Christopher Tate73e02522009-07-15 14:18:26 -0700588 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800589 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700590
Christopher Tate84725812010-02-04 15:52:40 -0800591 // Remember our ancestral dataset
592 mTokenFile = new File(mBaseStateDir, "ancestral");
593 try {
594 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800595 int version = tf.readInt();
596 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
597 mAncestralToken = tf.readLong();
598 mCurrentToken = tf.readLong();
599
600 int numPackages = tf.readInt();
601 if (numPackages >= 0) {
602 mAncestralPackages = new HashSet<String>();
603 for (int i = 0; i < numPackages; i++) {
604 String pkgName = tf.readUTF();
605 mAncestralPackages.add(pkgName);
606 }
607 }
608 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800609 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800610 } catch (FileNotFoundException fnf) {
611 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800612 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800613 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800614 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800615 }
616
Christopher Tatee97e8072009-07-15 16:45:50 -0700617 // Keep a log of what apps we've ever backed up. Because we might have
618 // rebooted in the middle of an operation that was removing something from
619 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700620 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700621 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700622
Christopher Tatee97e8072009-07-15 16:45:50 -0700623 // If we were in the middle of removing something from the ever-backed-up
624 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700625 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700626 if (tempProcessedFile.exists()) {
627 tempProcessedFile.delete();
628 }
629
Dan Egnor852f8e42009-09-30 11:20:45 -0700630 // If there are previous contents, parse them out then start a new
631 // file to continue the recordkeeping.
632 if (mEverStored.exists()) {
633 RandomAccessFile temp = null;
634 RandomAccessFile in = null;
635
636 try {
637 temp = new RandomAccessFile(tempProcessedFile, "rws");
638 in = new RandomAccessFile(mEverStored, "r");
639
640 while (true) {
641 PackageInfo info;
642 String pkg = in.readUTF();
643 try {
644 info = mPackageManager.getPackageInfo(pkg, 0);
645 mEverStoredApps.add(pkg);
646 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800647 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700648 } catch (NameNotFoundException e) {
649 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800650 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700651 }
652 }
653 } catch (EOFException e) {
654 // Once we've rewritten the backup history log, atomically replace the
655 // old one with the new one then reopen the file for continuing use.
656 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800657 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700658 }
659 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800660 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700661 } finally {
662 try { if (temp != null) temp.close(); } catch (IOException e) {}
663 try { if (in != null) in.close(); } catch (IOException e) {}
664 }
665 }
666
Christopher Tate73e02522009-07-15 14:18:26 -0700667 // Register for broadcasts about package install, etc., so we can
668 // update the provider list.
669 IntentFilter filter = new IntentFilter();
670 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
671 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
672 filter.addDataScheme("package");
673 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800674 // Register for events related to sdcard installation.
675 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800676 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
677 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800678 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700679 }
680
Christopher Tatecde87f42009-06-12 12:55:53 -0700681 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700682 for (File f : mJournalDir.listFiles()) {
683 if (mJournal == null || f.compareTo(mJournal) != 0) {
684 // This isn't the current journal, so it must be a leftover. Read
685 // out the package names mentioned there and schedule them for
686 // backup.
687 RandomAccessFile in = null;
688 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400689 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700690 in = new RandomAccessFile(f, "r");
691 while (true) {
692 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400693 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700694 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700695 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700696 } catch (EOFException e) {
697 // no more data; we're done
698 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800699 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700700 } finally {
701 // close/delete the file
702 try { if (in != null) in.close(); } catch (IOException e) {}
703 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700704 }
705 }
706 }
707 }
708
Christopher Tate4cc86e12009-09-21 19:36:51 -0700709 // Maintain persistent state around whether need to do an initialize operation.
710 // Must be called with the queue lock held.
711 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800712 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700713 + " on transport " + transportName);
714 try {
715 IBackupTransport transport = getTransport(transportName);
716 String transportDirName = transport.transportDirName();
717 File stateDir = new File(mBaseStateDir, transportDirName);
718 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
719
720 if (isPending) {
721 // We need an init before we can proceed with sending backup data.
722 // Record that with an entry in our set of pending inits, as well as
723 // journaling it via creation of a sentinel file.
724 mPendingInits.add(transportName);
725 try {
726 (new FileOutputStream(initPendingFile)).close();
727 } catch (IOException ioe) {
728 // Something is badly wrong with our permissions; just try to move on
729 }
730 } else {
731 // No more initialization needed; wipe the journal and reset our state.
732 initPendingFile.delete();
733 mPendingInits.remove(transportName);
734 }
735 } catch (RemoteException e) {
736 // can't happen; the transport is local
737 }
738 }
739
Christopher Tated55e18a2009-09-21 10:12:59 -0700740 // Reset all of our bookkeeping, in response to having been told that
741 // the backend data has been wiped [due to idle expiry, for example],
742 // so we must re-upload all saved settings.
743 void resetBackupState(File stateFileDir) {
744 synchronized (mQueueLock) {
745 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700746 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700747 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700748
Christopher Tate84725812010-02-04 15:52:40 -0800749 mCurrentToken = 0;
750 writeRestoreTokens();
751
Christopher Tated55e18a2009-09-21 10:12:59 -0700752 // Remove all the state files
753 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700754 // ... but don't touch the needs-init sentinel
755 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
756 sf.delete();
757 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700758 }
759
760 // Enqueue a new backup of every participant
761 int N = mBackupParticipants.size();
762 for (int i=0; i<N; i++) {
763 int uid = mBackupParticipants.keyAt(i);
764 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
765 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700766 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700767 }
768 }
769 }
770 }
771
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800772 // Add a transport to our set of available backends. If 'transport' is null, this
773 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700774 private void registerTransport(String name, IBackupTransport transport) {
775 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800776 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800777 if (transport != null) {
778 mTransports.put(name, transport);
779 } else {
780 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800781 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800782 mCurrentTransport = null;
783 }
784 // Nothing further to do in the unregistration case
785 return;
786 }
Christopher Tate91717492009-06-26 21:07:13 -0700787 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700788
789 // If the init sentinel file exists, we need to be sure to perform the init
790 // as soon as practical. We also create the state directory at registration
791 // time to ensure it's present from the outset.
792 try {
793 String transportName = transport.transportDirName();
794 File stateDir = new File(mBaseStateDir, transportName);
795 stateDir.mkdirs();
796
797 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
798 if (initSentinel.exists()) {
799 synchronized (mQueueLock) {
800 mPendingInits.add(transportName);
801
802 // TODO: pick a better starting time than now + 1 minute
803 long delay = 1000 * 60; // one minute, in milliseconds
804 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
805 System.currentTimeMillis() + delay, mRunInitIntent);
806 }
807 }
808 } catch (RemoteException e) {
809 // can't happen, the transport is local
810 }
Christopher Tate91717492009-06-26 21:07:13 -0700811 }
812
Christopher Tate3799bc22009-05-06 16:13:56 -0700813 // ----- Track installation/removal of packages -----
814 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
815 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700817
Christopher Tate3799bc22009-05-06 16:13:56 -0700818 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800819 boolean replacing = false;
820 boolean added = false;
821 Bundle extras = intent.getExtras();
822 String pkgList[] = null;
823 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
824 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
825 Uri uri = intent.getData();
826 if (uri == null) {
827 return;
828 }
829 String pkgName = uri.getSchemeSpecificPart();
830 if (pkgName != null) {
831 pkgList = new String[] { pkgName };
832 }
833 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
834 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800835 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800836 added = true;
837 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800838 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800839 added = false;
840 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
841 }
842 if (pkgList == null || pkgList.length == 0) {
843 return;
844 }
845 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700846 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800847 for (String pkgName : pkgList) {
848 if (replacing) {
849 // The package was just upgraded
850 updatePackageParticipantsLocked(pkgName);
851 } else {
852 // The package was just added
853 addPackageParticipantsLocked(pkgName);
854 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 }
856 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800857 } else {
858 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700859 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
860 } else {
861 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800862 for (String pkgName : pkgList) {
863 removePackageParticipantsLocked(pkgName);
864 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700865 }
866 }
867 }
868 }
869 };
870
Dan Egnor87a02bc2009-06-17 02:30:10 -0700871 // ----- Track connection to GoogleBackupTransport service -----
872 ServiceConnection mGoogleConnection = new ServiceConnection() {
873 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800874 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700875 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700876 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700877 }
878
879 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800880 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700881 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700882 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700883 }
884 };
885
Christopher Tate181fafa2009-05-14 11:12:14 -0700886 // Add the backup agents in the given package to our set of known backup participants.
887 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700888 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700889 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800890 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700891 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700892 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700893 }
894
Christopher Tate181fafa2009-05-14 11:12:14 -0700895 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700896 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700897 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800898 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700899 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800900 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700901 + " uid=" + p.applicationInfo.uid
902 + " killAfterRestore="
903 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700904 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700905 }
906 }
907
Dan Egnorefe52642009-06-24 00:16:33 -0700908 for (PackageInfo pkg : targetPkgs) {
909 if (packageName == null || pkg.packageName.equals(packageName)) {
910 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700911 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700912 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700913 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700914 mBackupParticipants.put(uid, set);
915 }
Dan Egnorefe52642009-06-24 00:16:33 -0700916 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700917
918 // If we've never seen this app before, schedule a backup for it
919 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800920 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700921 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700922 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700923 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700924 }
Christopher Tate487529a2009-04-29 14:03:25 -0700925 }
926 }
927
Christopher Tate6785dd82009-06-18 15:58:25 -0700928 // Remove the given package's entry from our known active set. If
929 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700930 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800931 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -0800932 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700933 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -0800934 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700935 } else {
936 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -0800937 List<PackageInfo> knownPackages = allAgentPackages();
938 for (PackageInfo pkg : knownPackages) {
939 allApps.add(pkg.packageName);
940 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700941 }
942 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700943 }
944
Joe Onorato8ad02812009-05-13 01:41:44 -0400945 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -0800946 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700947 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800948 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -0800949 + ") removing " + allPackageNames.size() + " entries");
950 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800951 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700952 }
953 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800954 for (String pkg : allPackageNames) {
955 if (packageName == null || pkg.equals(packageName)) {
956 int uid = -1;
957 try {
958 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
959 uid = info.applicationInfo.uid;
960 } catch (NameNotFoundException e) {
961 // we don't know this package name, so just skip it for now
962 continue;
963 }
964
Christopher Tate181fafa2009-05-14 11:12:14 -0700965 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700966 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700967 // Find the existing entry with the same package name, and remove it.
968 // We can't just remove(app) because the instances are different.
969 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -0800970 if (entry.packageName.equals(pkg)) {
971 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700972 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -0800973 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700974 break;
975 }
976 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700977 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700978 mBackupParticipants.delete(uid);
979 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700980 }
981 }
982 }
983 }
984
Christopher Tate181fafa2009-05-14 11:12:14 -0700985 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700986 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700987 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700988 int flags = PackageManager.GET_SIGNATURES;
989 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
990 int N = packages.size();
991 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700992 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700993 try {
994 ApplicationInfo app = pkg.applicationInfo;
995 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800996 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700997 packages.remove(a);
998 }
999 else {
1000 // we will need the shared library path, so look that up and store it here
1001 app = mPackageManager.getApplicationInfo(pkg.packageName,
1002 PackageManager.GET_SHARED_LIBRARY_FILES);
1003 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1004 }
1005 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001006 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001007 }
1008 }
Dan Egnorefe52642009-06-24 00:16:33 -07001009 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001010 }
Christopher Tateaa088442009-06-16 18:25:46 -07001011
Christopher Tate3799bc22009-05-06 16:13:56 -07001012 // Reset the given package's known backup participants. Unlike add/remove, the update
1013 // action cannot be passed a null package name.
1014 void updatePackageParticipantsLocked(String packageName) {
1015 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001016 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001017 return;
1018 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001020
1021 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001022 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001023 List<String> allAppNames = new ArrayList<String>();
1024 for (PackageInfo pkg : allApps) {
1025 allAppNames.add(pkg.packageName);
1026 }
1027 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001028 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001029 }
1030
Christopher Tate84725812010-02-04 15:52:40 -08001031 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001032 // backed up at least once
1033 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001034 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1035
1036 synchronized (mEverStoredApps) {
1037 if (!mEverStoredApps.add(packageName)) return;
1038
1039 RandomAccessFile out = null;
1040 try {
1041 out = new RandomAccessFile(mEverStored, "rws");
1042 out.seek(out.length());
1043 out.writeUTF(packageName);
1044 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001045 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001046 } finally {
1047 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001048 }
1049 }
1050 }
1051
Christopher Tatee97e8072009-07-15 16:45:50 -07001052 // Remove our awareness of having ever backed up the given package
1053 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001054 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001055
Dan Egnor852f8e42009-09-30 11:20:45 -07001056 synchronized (mEverStoredApps) {
1057 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1058 // we'll recognize on initialization time that the package no longer
1059 // exists and fix it up then.
1060 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1061 RandomAccessFile known = null;
1062 try {
1063 known = new RandomAccessFile(tempKnownFile, "rws");
1064 mEverStoredApps.remove(packageName);
1065 for (String s : mEverStoredApps) {
1066 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001067 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001068 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001069 known.close();
1070 known = null;
1071 if (!tempKnownFile.renameTo(mEverStored)) {
1072 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1073 }
1074 } catch (IOException e) {
1075 // Bad: we couldn't create the new copy. For safety's sake we
1076 // abandon the whole process and remove all what's-backed-up
1077 // state entirely, meaning we'll force a backup pass for every
1078 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001080 mEverStoredApps.clear();
1081 tempKnownFile.delete();
1082 mEverStored.delete();
1083 } finally {
1084 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001085 }
1086 }
1087 }
1088
Christopher Tateb49ceb32010-02-08 16:22:24 -08001089 // Persistently record the current and ancestral backup tokens as well
1090 // as the set of packages with data [supposedly] available in the
1091 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001092 void writeRestoreTokens() {
1093 try {
1094 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001095
1096 // First, the version number of this record, for futureproofing
1097 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1098
1099 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001100 af.writeLong(mAncestralToken);
1101 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001102
1103 // Now write the set of ancestral packages
1104 if (mAncestralPackages == null) {
1105 af.writeInt(-1);
1106 } else {
1107 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001109 for (String pkgName : mAncestralPackages) {
1110 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001111 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001112 }
1113 }
Christopher Tate84725812010-02-04 15:52:40 -08001114 af.close();
1115 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001116 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001117 }
1118 }
1119
Dan Egnor87a02bc2009-06-17 02:30:10 -07001120 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001121 private IBackupTransport getTransport(String transportName) {
1122 synchronized (mTransports) {
1123 IBackupTransport transport = mTransports.get(transportName);
1124 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001125 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001126 }
1127 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001128 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001129 }
1130
Christopher Tatedf01dea2009-06-09 20:45:02 -07001131 // fire off a backup agent, blocking until it attaches or times out
1132 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1133 IBackupAgent agent = null;
1134 synchronized(mAgentConnectLock) {
1135 mConnecting = true;
1136 mConnectedAgent = null;
1137 try {
1138 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001139 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001140
1141 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001142 // only wait 10 seconds for the clear data to happen
1143 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1144 while (mConnecting && mConnectedAgent == null
1145 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001146 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001147 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001148 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001149 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001150 return null;
1151 }
1152 }
1153
1154 // if we timed out with no connect, abort and move on
1155 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001156 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001157 return null;
1158 }
1159 agent = mConnectedAgent;
1160 }
1161 } catch (RemoteException e) {
1162 // can't happen
1163 }
1164 }
1165 return agent;
1166 }
1167
Christopher Tatec7b31e32009-06-10 15:49:30 -07001168 // clear an application's data, blocking until the operation completes or times out
1169 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001170 // Don't wipe packages marked allowClearUserData=false
1171 try {
1172 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1173 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001174 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001175 + packageName);
1176 return;
1177 }
1178 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001179 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001180 return;
1181 }
1182
Christopher Tatec7b31e32009-06-10 15:49:30 -07001183 ClearDataObserver observer = new ClearDataObserver();
1184
1185 synchronized(mClearDataLock) {
1186 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001187 try {
1188 mActivityManager.clearApplicationUserData(packageName, observer);
1189 } catch (RemoteException e) {
1190 // can't happen because the activity manager is in this process
1191 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001192
1193 // only wait 10 seconds for the clear data to happen
1194 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1195 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1196 try {
1197 mClearDataLock.wait(5000);
1198 } catch (InterruptedException e) {
1199 // won't happen, but still.
1200 mClearingData = false;
1201 }
1202 }
1203 }
1204 }
1205
1206 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001207 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001208 synchronized(mClearDataLock) {
1209 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001210 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001211 }
1212 }
1213 }
1214
Christopher Tate1bb69062010-02-19 17:02:12 -08001215 // Get the restore-set token for the best-available restore set for this package:
1216 // the active set if possible, else the ancestral one. Returns zero if none available.
1217 long getAvailableRestoreToken(String packageName) {
1218 long token = mAncestralToken;
1219 synchronized (mQueueLock) {
1220 if (mEverStoredApps.contains(packageName)) {
1221 token = mCurrentToken;
1222 }
1223 }
1224 return token;
1225 }
1226
Christopher Tate44a27902010-01-27 17:15:49 -08001227 // -----
1228 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1229 boolean waitUntilOperationComplete(int token) {
1230 int finalState = OP_PENDING;
1231 synchronized (mCurrentOpLock) {
1232 try {
1233 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1234 try {
1235 mCurrentOpLock.wait();
1236 } catch (InterruptedException e) {}
1237 }
1238 } catch (IndexOutOfBoundsException e) {
1239 // the operation has been mysteriously cleared from our
1240 // bookkeeping -- consider this a success and ignore it.
1241 }
1242 }
1243 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001244 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001245 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001246 return finalState == OP_ACKNOWLEDGED;
1247 }
1248
1249 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001250 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001251 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001252 mCurrentOperations.put(token, OP_PENDING);
1253 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1254 mBackupHandler.sendMessageDelayed(msg, interval);
1255 }
1256
Christopher Tate043dadc2009-06-02 16:11:00 -07001257 // ----- Back up a set of applications via a worker thread -----
1258
Christopher Tate44a27902010-01-27 17:15:49 -08001259 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001260 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001261 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001262 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001263 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001264 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001265
Christopher Tate44a27902010-01-27 17:15:49 -08001266 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001267 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001268 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001269 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001270 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001271
1272 try {
1273 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1274 } catch (RemoteException e) {
1275 // can't happen; the transport is local
1276 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001277 }
1278
Christopher Tate043dadc2009-06-02 16:11:00 -07001279 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001280 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001281 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001282 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001283
Christopher Tate79588342009-06-30 16:11:49 -07001284 // Backups run at background priority
1285 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1286
Christopher Tate043dadc2009-06-02 16:11:00 -07001287 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001288 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001289
Dan Egnor852f8e42009-09-30 11:20:45 -07001290 // If we haven't stored package manager metadata yet, we must init the transport.
1291 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1292 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001293 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001294 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001295 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001296 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001297 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001298 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001299 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001301 }
Dan Egnor01445162009-09-21 17:04:05 -07001302 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001303
1304 // The package manager doesn't have a proper <application> etc, but since
1305 // it's running here in the system process we can just set up its agent
1306 // directly and use a synthetic BackupRequest. We always run this pass
1307 // because it's cheap and this way we guarantee that we don't get out of
1308 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001309 if (status == BackupConstants.TRANSPORT_OK) {
1310 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1311 mPackageManager, allAgentPackages());
1312 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1313 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1314 status = processOneBackup(pmRequest,
1315 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1316 }
Christopher Tate90967f42009-09-20 15:28:33 -07001317
Dan Egnor01445162009-09-21 17:04:05 -07001318 if (status == BackupConstants.TRANSPORT_OK) {
1319 // Now run all the backups in our queue
1320 status = doQueuedBackups(mTransport);
1321 }
1322
1323 if (status == BackupConstants.TRANSPORT_OK) {
1324 // Tell the transport to finish everything it has buffered
1325 status = mTransport.finishBackup();
1326 if (status == BackupConstants.TRANSPORT_OK) {
1327 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001328 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001329 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001330 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001331 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001332 }
1333 }
1334
Dan Egnor01445162009-09-21 17:04:05 -07001335 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001336 // The backend reports that our dataset has been wiped. We need to
1337 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001338 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001339 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001340 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001341 }
1342 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001343 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001344 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001345 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001346 // If everything actually went through and this is the first time we've
1347 // done a backup, we can now record what the current backup dataset token
1348 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001349 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001350 try {
1351 mCurrentToken = mTransport.getCurrentRestoreSet();
1352 } catch (RemoteException e) { /* cannot happen */ }
1353 writeRestoreTokens();
1354 }
1355
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001356 // If things went wrong, we need to re-stage the apps we had expected
1357 // to be backing up in this pass. This journals the package names in
1358 // the current active pending-backup file, not in the we are holding
1359 // here in mJournal.
1360 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001361 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001362 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001363 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001364 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001365
1366 // We also want to reset the backup schedule based on whatever
1367 // the transport suggests by way of retry/backoff time.
1368 try {
1369 startBackupAlarmsLocked(mTransport.requestBackupTime());
1370 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001371 }
1372
1373 // Either backup was successful, in which case we of course do not need
1374 // this pass's journal any more; or it failed, in which case we just
1375 // re-enqueued all of these packages in the current active journal.
1376 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001377 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001378 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001379 }
1380
Christopher Tatec2af5d32010-02-02 15:18:58 -08001381 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001382 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001383 backupNow();
1384 }
1385
Dan Egnorbb9001c2009-07-27 12:20:13 -07001386 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001387 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001388 }
1389
Dan Egnor01445162009-09-21 17:04:05 -07001390 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001391 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001392 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001393
Christopher Tatec28083a2010-12-14 16:16:44 -08001394 // Verify that the requested app exists; it might be something that
1395 // requested a backup but was then uninstalled. The request was
1396 // journalled and rather than tamper with the journal it's safer
1397 // to sanity-check here.
1398 try {
1399 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1400 } catch (NameNotFoundException e) {
1401 Slog.d(TAG, "Package does not exist; skipping");
1402 continue;
1403 }
1404
Christopher Tate043dadc2009-06-02 16:11:00 -07001405 IBackupAgent agent = null;
1406 int mode = (request.fullBackup)
1407 ? IApplicationThread.BACKUP_MODE_FULL
1408 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1409 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001410 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001411 agent = bindToAgentSynchronous(request.appInfo, mode);
1412 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001413 int result = processOneBackup(request, agent, transport);
1414 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001415 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001416 } catch (SecurityException ex) {
1417 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001418 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001419 } finally {
1420 try { // unbind even on timeout, just in case
1421 mActivityManager.unbindBackupAgent(request.appInfo);
1422 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001423 }
1424 }
Dan Egnor01445162009-09-21 17:04:05 -07001425
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001426 mWakelock.setWorkSource(null);
1427
Dan Egnor01445162009-09-21 17:04:05 -07001428 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001429 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001430
Dan Egnor01445162009-09-21 17:04:05 -07001431 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1432 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001433 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001434 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001435
Dan Egnorbb9001c2009-07-27 12:20:13 -07001436 File savedStateName = new File(mStateDir, packageName);
1437 File backupDataName = new File(mDataDir, packageName + ".data");
1438 File newStateName = new File(mStateDir, packageName + ".new");
1439
1440 ParcelFileDescriptor savedState = null;
1441 ParcelFileDescriptor backupData = null;
1442 ParcelFileDescriptor newState = null;
1443
1444 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001445 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001446 try {
1447 // Look up the package info & signatures. This is first so that if it
1448 // throws an exception, there's no file setup yet that would need to
1449 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001450 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1451 // The metadata 'package' is synthetic
1452 packInfo = new PackageInfo();
1453 packInfo.packageName = packageName;
1454 } else {
1455 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001456 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001457 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001458
Christopher Tatec7b31e32009-06-10 15:49:30 -07001459 // In a full backup, we pass a null ParcelFileDescriptor as
1460 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001461 if (!request.fullBackup) {
1462 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001463 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001464 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1465 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001466
Dan Egnorbb9001c2009-07-27 12:20:13 -07001467 backupData = ParcelFileDescriptor.open(backupDataName,
1468 ParcelFileDescriptor.MODE_READ_WRITE |
1469 ParcelFileDescriptor.MODE_CREATE |
1470 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001471
Dan Egnorbb9001c2009-07-27 12:20:13 -07001472 newState = ParcelFileDescriptor.open(newStateName,
1473 ParcelFileDescriptor.MODE_READ_WRITE |
1474 ParcelFileDescriptor.MODE_CREATE |
1475 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001476
Christopher Tate44a27902010-01-27 17:15:49 -08001477 // Initiate the target's backup pass
1478 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1479 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1480 boolean success = waitUntilOperationComplete(token);
1481
1482 if (!success) {
1483 // timeout -- bail out into the failed-transaction logic
1484 throw new RuntimeException("Backup timeout");
1485 }
1486
Dan Egnorbb9001c2009-07-27 12:20:13 -07001487 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001489 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001490 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001492 backupDataName.delete();
1493 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001494 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001495 } finally {
1496 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1497 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1498 try { if (newState != null) newState.close(); } catch (IOException e) {}
1499 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001500 synchronized (mCurrentOpLock) {
1501 mCurrentOperations.clear();
1502 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001503 }
1504
1505 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001506 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001507 try {
1508 int size = (int) backupDataName.length();
1509 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001510 if (result == BackupConstants.TRANSPORT_OK) {
1511 backupData = ParcelFileDescriptor.open(backupDataName,
1512 ParcelFileDescriptor.MODE_READ_ONLY);
1513 result = transport.performBackup(packInfo, backupData);
1514 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001515
Dan Egnor83861e72009-09-17 16:17:55 -07001516 // TODO - We call finishBackup() for each application backed up, because
1517 // we need to know now whether it succeeded or failed. Instead, we should
1518 // hold off on finishBackup() until the end, which implies holding off on
1519 // renaming *all* the output state files (see below) until that happens.
1520
Dan Egnor01445162009-09-21 17:04:05 -07001521 if (result == BackupConstants.TRANSPORT_OK) {
1522 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001523 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001524 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001526 }
1527
1528 // After successful transport, delete the now-stale data
1529 // and juggle the files so that next time we supply the agent
1530 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001531 if (result == BackupConstants.TRANSPORT_OK) {
1532 backupDataName.delete();
1533 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001534 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001535 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001536 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001537 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001538 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001541 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001542 } finally {
1543 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001544 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001545
Dan Egnor01445162009-09-21 17:04:05 -07001546 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001547 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001548 }
1549
Christopher Tatedf01dea2009-06-09 20:45:02 -07001550
1551 // ----- Restore handling -----
1552
Christopher Tate78dd4a72009-11-04 11:49:08 -08001553 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1554 // If the target resides on the system partition, we allow it to restore
1555 // data from the like-named package in a restore set even if the signatures
1556 // do not match. (Unlike general applications, those flashed to the system
1557 // partition will be signed with the device's platform certificate, so on
1558 // different phones the same system app will have different signatures.)
1559 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001561 return true;
1562 }
1563
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001564 // Allow unsigned apps, but not signed on one device and unsigned on the other
1565 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001566 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001567 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001568 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001569 if ((storedSigs == null || storedSigs.length == 0)
1570 && (deviceSigs == null || deviceSigs.length == 0)) {
1571 return true;
1572 }
1573 if (storedSigs == null || deviceSigs == null) {
1574 return false;
1575 }
1576
Christopher Tateabce4e82009-06-18 18:35:32 -07001577 // !!! TODO: this demands that every stored signature match one
1578 // that is present on device, and does not demand the converse.
1579 // Is this this right policy?
1580 int nStored = storedSigs.length;
1581 int nDevice = deviceSigs.length;
1582
1583 for (int i=0; i < nStored; i++) {
1584 boolean match = false;
1585 for (int j=0; j < nDevice; j++) {
1586 if (storedSigs[i].equals(deviceSigs[j])) {
1587 match = true;
1588 break;
1589 }
1590 }
1591 if (!match) {
1592 return false;
1593 }
1594 }
1595 return true;
1596 }
1597
Christopher Tate44a27902010-01-27 17:15:49 -08001598 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001599 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001600 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001601 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001602 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001603 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001604 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001605 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001606
Christopher Tate5cbbf562009-06-22 16:44:51 -07001607 class RestoreRequest {
1608 public PackageInfo app;
1609 public int storedAppVersion;
1610
1611 RestoreRequest(PackageInfo _app, int _version) {
1612 app = _app;
1613 storedAppVersion = _version;
1614 }
1615 }
1616
Christopher Tate44a27902010-01-27 17:15:49 -08001617 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001618 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1619 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001620 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001621 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001622 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001623 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001624 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001625 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001626
1627 try {
1628 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1629 } catch (RemoteException e) {
1630 // can't happen; the transport is local
1631 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001632 }
1633
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001637 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001638 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001639
Christopher Tateb49ceb32010-02-08 16:22:24 -08001640 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001641 int error = -1; // assume error
1642
Dan Egnorefe52642009-06-24 00:16:33 -07001643 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001644 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001645 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001646 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001647
Dan Egnorefe52642009-06-24 00:16:33 -07001648 // Get the list of all packages which have backup enabled.
1649 // (Include the Package Manager metadata pseudo-package first.)
1650 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1651 PackageInfo omPackage = new PackageInfo();
1652 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1653 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001654
Dan Egnorefe52642009-06-24 00:16:33 -07001655 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001656 if (mTargetPackage == null) {
1657 restorePackages.addAll(agentPackages);
1658 } else {
1659 // Just one package to attempt restore of
1660 restorePackages.add(mTargetPackage);
1661 }
Dan Egnorefe52642009-06-24 00:16:33 -07001662
Christopher Tate7d562ec2009-06-25 18:03:43 -07001663 // let the observer know that we're running
1664 if (mObserver != null) {
1665 try {
1666 // !!! TODO: get an actual count from the transport after
1667 // its startRestore() runs?
1668 mObserver.restoreStarting(restorePackages.size());
1669 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001670 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001671 mObserver = null;
1672 }
1673 }
1674
Dan Egnor01445162009-09-21 17:04:05 -07001675 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1676 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001677 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001678 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001679 return;
1680 }
1681
1682 String packageName = mTransport.nextRestorePackage();
1683 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001685 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001686 return;
1687 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001689 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001690 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001691 return;
1692 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001693 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001694 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001695 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001696 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001697 return;
1698 }
1699
1700 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001701 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001702 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07001703 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
1704 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07001705
Christopher Tate8c032472009-07-02 14:28:47 -07001706 // Verify that the backup set includes metadata. If not, we can't do
1707 // signature/version verification etc, so we simply do not proceed with
1708 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001709 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001710 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001711 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001712 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001713 return;
1714 }
1715
Christopher Tate7d562ec2009-06-25 18:03:43 -07001716 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001717 for (;;) {
1718 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001719
Dan Egnorefe52642009-06-24 00:16:33 -07001720 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001721 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001722 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001723 return;
1724 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001725 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001726 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001727 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001728
Christopher Tate7d562ec2009-06-25 18:03:43 -07001729 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001730 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001731 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001732 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001733 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001734 mObserver = null;
1735 }
1736 }
1737
Dan Egnorefe52642009-06-24 00:16:33 -07001738 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1739 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001740 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001742 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001743 continue;
1744 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001745
Dan Egnorbb9001c2009-07-27 12:20:13 -07001746 PackageInfo packageInfo;
1747 try {
1748 int flags = PackageManager.GET_SIGNATURES;
1749 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1750 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001751 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001752 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001753 "Package missing on device");
1754 continue;
1755 }
1756
Dan Egnorefe52642009-06-24 00:16:33 -07001757 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001758 // Data is from a "newer" version of the app than we have currently
1759 // installed. If the app has not declared that it is prepared to
1760 // handle this case, we do not attempt the restore.
1761 if ((packageInfo.applicationInfo.flags
1762 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1763 String message = "Version " + metaInfo.versionCode
1764 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001765 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001766 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1767 packageName, message);
1768 continue;
1769 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001770 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001771 + " > installed " + packageInfo.versionCode
1772 + " but restoreAnyVersion");
1773 }
Dan Egnorefe52642009-06-24 00:16:33 -07001774 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001775
Christopher Tate78dd4a72009-11-04 11:49:08 -08001776 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001777 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001779 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001780 continue;
1781 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001782
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001784 + " restore version [" + metaInfo.versionCode
1785 + "] is compatible with installed version ["
1786 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001787
Christopher Tate3de55bc2010-03-12 17:28:08 -08001788 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001789 IBackupAgent agent = bindToAgentSynchronous(
1790 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001791 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001792 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001795 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001796 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001797 }
1798
Christopher Tate5e1ab332009-09-01 20:32:49 -07001799 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001800 try {
Chris Tate249345b2010-10-29 12:57:04 -07001801 processOneRestore(packageInfo, metaInfo.versionCode, agent,
1802 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001803 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001804 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001805 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001806 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001807
1808 // The agent was probably running with a stub Application object,
1809 // which isn't a valid run mode for the main app logic. Shut
1810 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001811 // usual full initialization. Note that this is only done for
1812 // full-system restores: when a single app has requested a restore,
1813 // it is explicitly not killed following that operation.
1814 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001815 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001816 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001817 + packageInfo.applicationInfo.processName);
1818 mActivityManager.killApplicationProcess(
1819 packageInfo.applicationInfo.processName,
1820 packageInfo.applicationInfo.uid);
1821 }
Dan Egnorefe52642009-06-24 00:16:33 -07001822 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001823 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001824
1825 // if we get this far, report success to the observer
1826 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001827 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001828 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001829 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001830 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001831 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001832 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833
Dan Egnorefe52642009-06-24 00:16:33 -07001834 try {
1835 mTransport.finishRestore();
1836 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001837 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001838 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001839
1840 if (mObserver != null) {
1841 try {
1842 mObserver.restoreFinished(error);
1843 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001844 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001845 }
1846 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001847
Christopher Tate84725812010-02-04 15:52:40 -08001848 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001849 // ancestral dataset, as well as the set of apps that are possibly
1850 // restoreable from the dataset
1851 if (mTargetPackage == null && pmAgent != null) {
1852 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001853 mAncestralToken = mToken;
1854 writeRestoreTokens();
1855 }
1856
Christopher Tate1bb69062010-02-19 17:02:12 -08001857 // We must under all circumstances tell the Package Manager to
1858 // proceed with install notifications if it's waiting for us.
1859 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001860 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001861 try {
1862 mPackageManagerBinder.finishPackageInstall(mPmToken);
1863 } catch (RemoteException e) { /* can't happen */ }
1864 }
1865
Christopher Tate73a3cb32010-12-13 18:27:26 -08001866 // Furthermore we need to reset the session timeout clock
1867 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
1868 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
1869 TIMEOUT_RESTORE_INTERVAL);
1870
Christopher Tateb6787f22009-07-02 17:40:45 -07001871 // done; we can finally release the wakelock
1872 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001873 }
1874 }
1875
Dan Egnorefe52642009-06-24 00:16:33 -07001876 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07001877 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
1878 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001879 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001880 final String packageName = app.packageName;
1881
Joe Onorato8a9b2202010-02-26 18:56:32 -08001882 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001883
Christopher Tatec7b31e32009-06-10 15:49:30 -07001884 // !!! TODO: get the dirs from the transport
1885 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001886 File newStateName = new File(mStateDir, packageName + ".new");
1887 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001888
Dan Egnorbb9001c2009-07-27 12:20:13 -07001889 ParcelFileDescriptor backupData = null;
1890 ParcelFileDescriptor newState = null;
1891
Christopher Tate44a27902010-01-27 17:15:49 -08001892 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001893 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001894 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001895 backupData = ParcelFileDescriptor.open(backupDataName,
1896 ParcelFileDescriptor.MODE_READ_WRITE |
1897 ParcelFileDescriptor.MODE_CREATE |
1898 ParcelFileDescriptor.MODE_TRUNCATE);
1899
Dan Egnor01445162009-09-21 17:04:05 -07001900 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001901 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001902 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001903 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001904 }
1905
1906 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001907 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001908 backupData = ParcelFileDescriptor.open(backupDataName,
1909 ParcelFileDescriptor.MODE_READ_ONLY);
1910
Dan Egnorbb9001c2009-07-27 12:20:13 -07001911 newState = ParcelFileDescriptor.open(newStateName,
1912 ParcelFileDescriptor.MODE_READ_WRITE |
1913 ParcelFileDescriptor.MODE_CREATE |
1914 ParcelFileDescriptor.MODE_TRUNCATE);
1915
Christopher Tate44a27902010-01-27 17:15:49 -08001916 // Kick off the restore, checking for hung agents
1917 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1918 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1919 boolean success = waitUntilOperationComplete(token);
1920
1921 if (!success) {
1922 throw new RuntimeException("restore timeout");
1923 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001924
1925 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001926 //
1927 // !!! TODO: the restored data should be migrated on the server
1928 // side into the current dataset. In that case the new state file
1929 // we just created would reflect the data already extant in the
1930 // backend, so there'd be nothing more to do. Until that happens,
1931 // however, we need to make sure that we record the data to the
1932 // current backend dataset. (Yes, this means shipping the data over
1933 // the wire in both directions. That's bad, but consistency comes
1934 // first, then efficiency.) Once we introduce server-side data
1935 // migration to the newly-restored device's dataset, we will change
1936 // the following from a discard of the newly-written state to the
1937 // "correct" operation of renaming into the canonical state blob.
1938 newStateName.delete(); // TODO: remove; see above comment
1939 //newStateName.renameTo(savedStateName); // TODO: replace with this
1940
Dan Egnorbb9001c2009-07-27 12:20:13 -07001941 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001942 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001943 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001944 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001945 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001946
Christopher Tate96733042009-07-20 14:49:13 -07001947 // If the agent fails restore, it might have put the app's data
1948 // into an incoherent state. For consistency we wipe its data
1949 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001950 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001951 } finally {
1952 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001953 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1954 try { if (newState != null) newState.close(); } catch (IOException e) {}
1955 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001956 mCurrentOperations.delete(token);
Chris Tate249345b2010-10-29 12:57:04 -07001957
1958 // If we know a priori that we'll need to perform a full post-restore backup
1959 // pass, clear the new state file data. This means we're discarding work that
1960 // was just done by the app's agent, but this way the agent doesn't need to
1961 // take any special action based on global device state.
1962 if (needFullBackup) {
1963 newStateName.delete();
1964 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001965 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001966 }
1967 }
1968
Christopher Tate44a27902010-01-27 17:15:49 -08001969 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001970 IBackupTransport mTransport;
1971 PackageInfo mPackage;
1972
Christopher Tate44a27902010-01-27 17:15:49 -08001973 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001974 mTransport = transport;
1975 mPackage = packageInfo;
1976 }
1977
Christopher Tateee0e78a2009-07-02 11:17:03 -07001978 public void run() {
1979 try {
1980 // Clear the on-device backup state to ensure a full backup next time
1981 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1982 File stateFile = new File(stateDir, mPackage.packageName);
1983 stateFile.delete();
1984
1985 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001986 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001987 mTransport.clearBackupData(mPackage);
1988 } catch (RemoteException e) {
1989 // can't happen; the transport is local
1990 } finally {
1991 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001992 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001993 mTransport.finishBackup();
1994 } catch (RemoteException e) {
1995 // can't happen; the transport is local
1996 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001997
1998 // Last but not least, release the cpu
1999 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002000 }
2001 }
2002 }
2003
Christopher Tate44a27902010-01-27 17:15:49 -08002004 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002005 HashSet<String> mQueue;
2006
Christopher Tate44a27902010-01-27 17:15:49 -08002007 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002008 mQueue = transportNames;
2009 }
2010
Christopher Tate4cc86e12009-09-21 19:36:51 -07002011 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002012 try {
2013 for (String transportName : mQueue) {
2014 IBackupTransport transport = getTransport(transportName);
2015 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002016 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002017 continue;
2018 }
2019
Joe Onorato8a9b2202010-02-26 18:56:32 -08002020 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002021 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002022 long startRealtime = SystemClock.elapsedRealtime();
2023 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002024
Christopher Tate4cc86e12009-09-21 19:36:51 -07002025 if (status == BackupConstants.TRANSPORT_OK) {
2026 status = transport.finishBackup();
2027 }
2028
2029 // Okay, the wipe really happened. Clean up our local bookkeeping.
2030 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002031 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002032 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002033 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002034 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002035 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002036 synchronized (mQueueLock) {
2037 recordInitPendingLocked(false, transportName);
2038 }
Dan Egnor726247c2009-09-29 19:12:31 -07002039 } else {
2040 // If this didn't work, requeue this one and try again
2041 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002042 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002043 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002044 synchronized (mQueueLock) {
2045 recordInitPendingLocked(true, transportName);
2046 }
2047 // do this via another alarm to make sure of the wakelock states
2048 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002049 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002050 + transportName + " resched in " + delay);
2051 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2052 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002053 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002054 }
2055 } catch (RemoteException e) {
2056 // can't happen; the transports are local
2057 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002058 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002059 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002060 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002061 mWakelock.release();
2062 }
2063 }
2064 }
2065
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002066 private void dataChangedImpl(String packageName) {
2067 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2068 dataChangedImpl(packageName, targets);
2069 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002070
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002071 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002072 // Record that we need a backup pass for the caller. Since multiple callers
2073 // may share a uid, we need to note all candidates within that uid and schedule
2074 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002075 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002076
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002077 if (targets == null) {
2078 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2079 + " uid=" + Binder.getCallingUid());
2080 return;
2081 }
2082
2083 synchronized (mQueueLock) {
2084 // Note that this client has made data changes that need to be backed up
2085 for (ApplicationInfo app : targets) {
2086 // validate the caller-supplied package name against the known set of
2087 // packages associated with this uid
2088 if (app.packageName.equals(packageName)) {
2089 // Add the caller to the set of pending backups. If there is
2090 // one already there, then overwrite it, but no harm done.
2091 BackupRequest req = new BackupRequest(app, false);
Christopher Tatec28083a2010-12-14 16:16:44 -08002092 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002093 // Journal this request in case of crash. The put()
2094 // operation returned null when this package was not already
2095 // in the set; we want to avoid touching the disk redundantly.
2096 writeToJournalLocked(packageName);
2097
2098 if (DEBUG) {
2099 int numKeys = mPendingBackups.size();
2100 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2101 for (BackupRequest b : mPendingBackups.values()) {
2102 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2103 }
2104 }
2105 }
2106 }
2107 }
2108 }
2109 }
2110
2111 // Note: packageName is currently unused, but may be in the future
2112 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002113 // If the caller does not hold the BACKUP permission, it can only request a
2114 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002115 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002116 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002117 synchronized (mBackupParticipants) {
2118 return mBackupParticipants.get(Binder.getCallingUid());
2119 }
2120 }
2121
2122 // a caller with full permission can ask to back up any participating app
2123 // !!! TODO: allow backup of ANY app?
2124 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2125 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002126 int N = mBackupParticipants.size();
2127 for (int i = 0; i < N; i++) {
2128 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2129 if (s != null) {
2130 targets.addAll(s);
2131 }
2132 }
2133 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002134 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002135 }
Christopher Tate46758122009-05-06 11:22:00 -07002136
Christopher Tatecde87f42009-06-12 12:55:53 -07002137 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002138 RandomAccessFile out = null;
2139 try {
2140 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2141 out = new RandomAccessFile(mJournal, "rws");
2142 out.seek(out.length());
2143 out.writeUTF(str);
2144 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002145 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002146 mJournal = null;
2147 } finally {
2148 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002149 }
2150 }
2151
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002152 // ----- IBackupManager binder interface -----
2153
2154 public void dataChanged(final String packageName) {
2155 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2156 if (targets == null) {
2157 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2158 + " uid=" + Binder.getCallingUid());
2159 return;
2160 }
2161
2162 mBackupHandler.post(new Runnable() {
2163 public void run() {
2164 dataChangedImpl(packageName, targets);
2165 }
2166 });
2167 }
2168
Christopher Tateee0e78a2009-07-02 11:17:03 -07002169 // Clear the given package's backup data from the current transport
2170 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002171 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002172 PackageInfo info;
2173 try {
2174 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2175 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002176 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002177 return;
2178 }
2179
2180 // If the caller does not hold the BACKUP permission, it can only request a
2181 // wipe of its own backed-up data.
2182 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002183 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002184 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2185 apps = mBackupParticipants.get(Binder.getCallingUid());
2186 } else {
2187 // a caller with full permission can ask to back up any participating app
2188 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002189 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002190 apps = new HashSet<ApplicationInfo>();
2191 int N = mBackupParticipants.size();
2192 for (int i = 0; i < N; i++) {
2193 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2194 if (s != null) {
2195 apps.addAll(s);
2196 }
2197 }
2198 }
2199
2200 // now find the given package in the set of candidate apps
2201 for (ApplicationInfo app : apps) {
2202 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002203 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002204 // found it; fire off the clear request
2205 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002206 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002207 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002208 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2209 new ClearParams(getTransport(mCurrentTransport), info));
2210 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002211 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002212 }
2213 break;
2214 }
2215 }
2216 }
2217
Christopher Tateace7f092009-06-15 18:07:25 -07002218 // Run a backup pass immediately for any applications that have declared
2219 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002220 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002221 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002222
Joe Onorato8a9b2202010-02-26 18:56:32 -08002223 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002224 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002225 // Because the alarms we are using can jitter, and we want an *immediate*
2226 // backup pass to happen, we restart the timer beginning with "next time,"
2227 // then manually fire the backup trigger intent ourselves.
2228 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002229 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002230 mRunBackupIntent.send();
2231 } catch (PendingIntent.CanceledException e) {
2232 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002233 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002234 }
Christopher Tate46758122009-05-06 11:22:00 -07002235 }
2236 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002237
Christopher Tate8031a3d2009-07-06 16:36:05 -07002238 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002239 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2241 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002242
Joe Onorato8a9b2202010-02-26 18:56:32 -08002243 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002244
Christopher Tate6ef58a12009-06-29 14:56:28 -07002245 boolean wasEnabled = mEnabled;
2246 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002247 Settings.Secure.putInt(mContext.getContentResolver(),
2248 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002249 mEnabled = enable;
2250 }
2251
Christopher Tate49401dd2009-07-01 12:34:29 -07002252 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002253 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002254 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002255 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002256 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002257 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002258 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002259
Christopher Tateb6787f22009-07-02 17:40:45 -07002260 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002261
2262 // This also constitutes an opt-out, so we wipe any data for
2263 // this device from the backend. We start that process with
2264 // an alarm in order to guarantee wakelock states.
2265 if (wasEnabled && mProvisioned) {
2266 // NOTE: we currently flush every registered transport, not just
2267 // the currently-active one.
2268 HashSet<String> allTransports;
2269 synchronized (mTransports) {
2270 allTransports = new HashSet<String>(mTransports.keySet());
2271 }
2272 // build the set of transports for which we are posting an init
2273 for (String transport : allTransports) {
2274 recordInitPendingLocked(true, transport);
2275 }
2276 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2277 mRunInitIntent);
2278 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002279 }
2280 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002281 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002282
Christopher Tatecce9da52010-02-03 15:11:15 -08002283 // Enable/disable automatic restore of app data at install time
2284 public void setAutoRestore(boolean doAutoRestore) {
2285 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2286 "setBackupEnabled");
2287
Joe Onorato8a9b2202010-02-26 18:56:32 -08002288 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002289
2290 synchronized (this) {
2291 Settings.Secure.putInt(mContext.getContentResolver(),
2292 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2293 mAutoRestore = doAutoRestore;
2294 }
2295 }
2296
Christopher Tate8031a3d2009-07-06 16:36:05 -07002297 // Mark the backup service as having been provisioned
2298 public void setBackupProvisioned(boolean available) {
2299 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2300 "setBackupProvisioned");
2301
2302 boolean wasProvisioned = mProvisioned;
2303 synchronized (this) {
2304 Settings.Secure.putInt(mContext.getContentResolver(),
2305 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2306 mProvisioned = available;
2307 }
2308
2309 synchronized (mQueueLock) {
2310 if (available && !wasProvisioned && mEnabled) {
2311 // we're now good to go, so start the backup alarms
2312 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2313 } else if (!available) {
2314 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002315 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002316 mAlarmManager.cancel(mRunBackupIntent);
2317 }
2318 }
2319 }
2320
2321 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002322 // We used to use setInexactRepeating(), but that may be linked to
2323 // backups running at :00 more often than not, creating load spikes.
2324 // Schedule at an exact time for now, and also add a bit of "fuzz".
2325
2326 Random random = new Random();
2327 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2328 random.nextInt(FUZZ_MILLIS);
2329 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2330 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002331 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002332 }
2333
Christopher Tate6ef58a12009-06-29 14:56:28 -07002334 // Report whether the backup mechanism is currently enabled
2335 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002337 return mEnabled; // no need to synchronize just to read it
2338 }
2339
Christopher Tate91717492009-06-26 21:07:13 -07002340 // Report the name of the currently active transport
2341 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002342 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002343 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002344 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002345 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002346 }
2347
Christopher Tate91717492009-06-26 21:07:13 -07002348 // Report all known, available backup transports
2349 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002351
Christopher Tate91717492009-06-26 21:07:13 -07002352 String[] list = null;
2353 ArrayList<String> known = new ArrayList<String>();
2354 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2355 if (entry.getValue() != null) {
2356 known.add(entry.getKey());
2357 }
2358 }
2359
2360 if (known.size() > 0) {
2361 list = new String[known.size()];
2362 known.toArray(list);
2363 }
2364 return list;
2365 }
2366
2367 // Select which transport to use for the next backup operation. If the given
2368 // name is not one of the available transports, no action is taken and the method
2369 // returns null.
2370 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002371 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002372
2373 synchronized (mTransports) {
2374 String prevTransport = null;
2375 if (mTransports.get(transport) != null) {
2376 prevTransport = mCurrentTransport;
2377 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002378 Settings.Secure.putString(mContext.getContentResolver(),
2379 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002380 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002381 + " returning " + prevTransport);
2382 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002383 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002384 }
2385 return prevTransport;
2386 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002387 }
2388
Christopher Tatef5e1c292010-12-08 18:40:26 -08002389 // Supply the configuration Intent for the given transport. If the name is not one
2390 // of the available transports, or if the transport does not supply any configuration
2391 // UI, the method returns null.
2392 public Intent getConfigurationIntent(String transportName) {
2393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2394 "getConfigurationIntent");
2395
2396 synchronized (mTransports) {
2397 final IBackupTransport transport = mTransports.get(transportName);
2398 if (transport != null) {
2399 try {
2400 final Intent intent = transport.configurationIntent();
2401 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2402 + intent);
2403 return intent;
2404 } catch (RemoteException e) {
2405 /* fall through to return null */
2406 }
2407 }
2408 }
2409
2410 return null;
2411 }
2412
2413 // Supply the configuration summary string for the given transport. If the name is
2414 // not one of the available transports, or if the transport does not supply any
2415 // summary / destination string, the method can return null.
2416 //
2417 // This string is used VERBATIM as the summary text of the relevant Settings item!
2418 public String getDestinationString(String transportName) {
2419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2420 "getConfigurationIntent");
2421
2422 synchronized (mTransports) {
2423 final IBackupTransport transport = mTransports.get(transportName);
2424 if (transport != null) {
2425 try {
2426 final String text = transport.currentDestinationString();
2427 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2428 return text;
2429 } catch (RemoteException e) {
2430 /* fall through to return null */
2431 }
2432 }
2433 }
2434
2435 return null;
2436 }
2437
Christopher Tate043dadc2009-06-02 16:11:00 -07002438 // Callback: a requested backup agent has been instantiated. This should only
2439 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002440 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002441 synchronized(mAgentConnectLock) {
2442 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002443 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002444 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2445 mConnectedAgent = agent;
2446 mConnecting = false;
2447 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002448 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002449 + " claiming agent connected");
2450 }
2451 mAgentConnectLock.notifyAll();
2452 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002453 }
2454
2455 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2456 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002457 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002458 public void agentDisconnected(String packageName) {
2459 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002460 synchronized(mAgentConnectLock) {
2461 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2462 mConnectedAgent = null;
2463 mConnecting = false;
2464 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002465 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002466 + " claiming agent disconnected");
2467 }
2468 mAgentConnectLock.notifyAll();
2469 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002470 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002471
Christopher Tate1bb69062010-02-19 17:02:12 -08002472 // An application being installed will need a restore pass, then the Package Manager
2473 // will need to be told when the restore is finished.
2474 public void restoreAtInstall(String packageName, int token) {
2475 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002476 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002477 + " attemping install-time restore");
2478 return;
2479 }
2480
2481 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002482 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002483 + " token=" + Integer.toHexString(token));
2484
Christopher Tatef0872722010-02-25 15:22:48 -08002485 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002486 // okay, we're going to attempt a restore of this package from this restore set.
2487 // The eventual message back into the Package Manager to run the post-install
2488 // steps for 'token' will be issued from the restore handling code.
2489
2490 // We can use a synthetic PackageInfo here because:
2491 // 1. We know it's valid, since the Package Manager supplied the name
2492 // 2. Only the packageName field will be used by the restore code
2493 PackageInfo pkg = new PackageInfo();
2494 pkg.packageName = packageName;
2495
2496 mWakelock.acquire();
2497 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2498 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002499 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002500 mBackupHandler.sendMessage(msg);
2501 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002502 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2503 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002504 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002505 try {
2506 mPackageManagerBinder.finishPackageInstall(token);
2507 } catch (RemoteException e) { /* can't happen */ }
2508 }
2509 }
2510
Christopher Tate8c850b72009-06-07 19:33:20 -07002511 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002512 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2513 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2514 + " transport=" + transport);
2515
2516 boolean needPermission = true;
2517 if (transport == null) {
2518 transport = mCurrentTransport;
2519
2520 if (packageName != null) {
2521 PackageInfo app = null;
2522 try {
2523 app = mPackageManager.getPackageInfo(packageName, 0);
2524 } catch (NameNotFoundException nnf) {
2525 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2526 throw new IllegalArgumentException("Package " + packageName + " not found");
2527 }
2528
2529 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2530 // So: using the current active transport, and the caller has asked
2531 // that its own package will be restored. In this narrow use case
2532 // we do not require the caller to hold the permission.
2533 needPermission = false;
2534 }
2535 }
2536 }
2537
2538 if (needPermission) {
2539 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2540 "beginRestoreSession");
2541 } else {
2542 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2543 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002544
2545 synchronized(this) {
2546 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002547 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002548 return null;
2549 }
Chris Tate44ab8452010-11-16 15:10:49 -08002550 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08002551 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07002552 }
2553 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002554 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002555
Christopher Tate73a3cb32010-12-13 18:27:26 -08002556 void clearRestoreSession(ActiveRestoreSession currentSession) {
2557 synchronized(this) {
2558 if (currentSession != mActiveRestoreSession) {
2559 Slog.e(TAG, "ending non-current restore session");
2560 } else {
2561 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
2562 mActiveRestoreSession = null;
2563 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2564 }
2565 }
2566 }
2567
Christopher Tate44a27902010-01-27 17:15:49 -08002568 // Note that a currently-active backup agent has notified us that it has
2569 // completed the given outstanding asynchronous backup/restore operation.
2570 public void opComplete(int token) {
2571 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002572 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002573 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2574 mCurrentOpLock.notifyAll();
2575 }
2576 }
2577
Christopher Tate9b3905c2009-06-08 15:24:01 -07002578 // ----- Restore session -----
2579
Christopher Tate80202c82010-01-25 19:37:47 -08002580 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002581 private static final String TAG = "RestoreSession";
2582
Chris Tate44ab8452010-11-16 15:10:49 -08002583 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002584 private IBackupTransport mRestoreTransport = null;
2585 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08002586 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002587
Chris Tate44ab8452010-11-16 15:10:49 -08002588 ActiveRestoreSession(String packageName, String transport) {
2589 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07002590 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002591 }
2592
2593 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002594 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002596 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002597 if (observer == null) {
2598 throw new IllegalArgumentException("Observer must not be null");
2599 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002600
Christopher Tate73a3cb32010-12-13 18:27:26 -08002601 if (mEnded) {
2602 throw new IllegalStateException("Restore session already ended");
2603 }
2604
Christopher Tate1bb69062010-02-19 17:02:12 -08002605 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002606 try {
Christopher Tate43383042009-07-13 15:17:13 -07002607 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002609 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002610 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002611 // spin off the transport request to our service thread
2612 mWakelock.acquire();
2613 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2614 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2615 mBackupHandler.sendMessage(msg);
2616 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002617 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002618 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002619 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002620 } finally {
2621 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002622 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002623 }
2624
Christopher Tate84725812010-02-04 15:52:40 -08002625 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2627 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002628
Chris Tate44ab8452010-11-16 15:10:49 -08002629 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002630 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002631
Christopher Tate73a3cb32010-12-13 18:27:26 -08002632 if (mEnded) {
2633 throw new IllegalStateException("Restore session already ended");
2634 }
2635
Dan Egnor0084da52009-07-29 12:57:16 -07002636 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08002637 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
2638 return -1;
2639 }
2640
2641 if (mPackageName != null) {
2642 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07002643 return -1;
2644 }
2645
Christopher Tate21ab6a52009-09-24 18:01:46 -07002646 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002647 for (int i = 0; i < mRestoreSets.length; i++) {
2648 if (token == mRestoreSets[i].token) {
2649 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002650 mWakelock.acquire();
2651 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002652 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07002653 mBackupHandler.sendMessage(msg);
2654 Binder.restoreCallingIdentity(oldId);
2655 return 0;
2656 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002657 }
2658 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002659
Joe Onorato8a9b2202010-02-26 18:56:32 -08002660 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002661 return -1;
2662 }
2663
Christopher Tate84725812010-02-04 15:52:40 -08002664 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002665 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002666
Christopher Tate73a3cb32010-12-13 18:27:26 -08002667 if (mEnded) {
2668 throw new IllegalStateException("Restore session already ended");
2669 }
2670
Chris Tate44ab8452010-11-16 15:10:49 -08002671 if (mPackageName != null) {
2672 if (! mPackageName.equals(packageName)) {
2673 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
2674 + " on session for package " + mPackageName);
2675 return -1;
2676 }
2677 }
2678
Christopher Tate84725812010-02-04 15:52:40 -08002679 PackageInfo app = null;
2680 try {
2681 app = mPackageManager.getPackageInfo(packageName, 0);
2682 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002683 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002684 return -1;
2685 }
2686
2687 // If the caller is not privileged and is not coming from the target
2688 // app's uid, throw a permission exception back to the caller.
2689 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2690 Binder.getCallingPid(), Binder.getCallingUid());
2691 if ((perm == PackageManager.PERMISSION_DENIED) &&
2692 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002693 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002694 + " or calling uid=" + Binder.getCallingUid());
2695 throw new SecurityException("No permission to restore other packages");
2696 }
2697
Christopher Tate7d411a32010-02-26 11:27:08 -08002698 // If the package has no backup agent, we obviously cannot proceed
2699 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002700 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002701 return -1;
2702 }
2703
Christopher Tate84725812010-02-04 15:52:40 -08002704 // So far so good; we're allowed to try to restore this package. Now
2705 // check whether there is data for it in the current dataset, falling back
2706 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002707 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002708
2709 // If we didn't come up with a place to look -- no ancestral dataset and
2710 // the app has never been backed up from this device -- there's nothing
2711 // to do but return failure.
2712 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08002713 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08002714 return -1;
2715 }
2716
2717 // Ready to go: enqueue the restore request and claim success
2718 long oldId = Binder.clearCallingIdentity();
2719 mWakelock.acquire();
2720 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002721 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08002722 mBackupHandler.sendMessage(msg);
2723 Binder.restoreCallingIdentity(oldId);
2724 return 0;
2725 }
2726
Christopher Tate73a3cb32010-12-13 18:27:26 -08002727 // Posted to the handler to tear down a restore session in a cleanly synchronized way
2728 class EndRestoreRunnable implements Runnable {
2729 BackupManagerService mBackupManager;
2730 ActiveRestoreSession mSession;
2731
2732 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
2733 mBackupManager = manager;
2734 mSession = session;
2735 }
2736
2737 public void run() {
2738 // clean up the session's bookkeeping
2739 synchronized (mSession) {
2740 try {
2741 if (mSession.mRestoreTransport != null) {
2742 mSession.mRestoreTransport.finishRestore();
2743 }
2744 } catch (Exception e) {
2745 Slog.e(TAG, "Error in finishRestore", e);
2746 } finally {
2747 mSession.mRestoreTransport = null;
2748 mSession.mEnded = true;
2749 }
2750 }
2751
2752 // clean up the BackupManagerService side of the bookkeeping
2753 // and cancel any pending timeout message
2754 mBackupManager.clearRestoreSession(mSession);
2755 }
2756 }
2757
Dan Egnor0084da52009-07-29 12:57:16 -07002758 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002759 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002760
Christopher Tate73a3cb32010-12-13 18:27:26 -08002761 if (mEnded) {
2762 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07002763 }
2764
Christopher Tate73a3cb32010-12-13 18:27:26 -08002765 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07002766 }
2767 }
2768
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002769 @Override
2770 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002771 long identityToken = Binder.clearCallingIdentity();
2772 try {
2773 dumpInternal(pw);
2774 } finally {
2775 Binder.restoreCallingIdentity(identityToken);
2776 }
2777 }
2778
2779 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002780 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002781 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002782 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002783 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002784 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002785 pw.println("Last backup pass: " + mLastBackupPass
2786 + " (now = " + System.currentTimeMillis() + ')');
2787 pw.println(" next scheduled: " + mNextBackupPass);
2788
Christopher Tate91717492009-06-26 21:07:13 -07002789 pw.println("Available transports:");
2790 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002791 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2792 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002793 IBackupTransport transport = getTransport(t);
2794 File dir = new File(mBaseStateDir, transport.transportDirName());
2795 pw.println(" destination: " + transport.currentDestinationString());
2796 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07002797 for (File f : dir.listFiles()) {
2798 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2799 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08002800 } catch (Exception e) {
2801 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002802 pw.println(" Error: " + e);
2803 }
Christopher Tate91717492009-06-26 21:07:13 -07002804 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002805
2806 pw.println("Pending init: " + mPendingInits.size());
2807 for (String s : mPendingInits) {
2808 pw.println(" " + s);
2809 }
2810
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002811 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002812 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002813 for (int i=0; i<N; i++) {
2814 int uid = mBackupParticipants.keyAt(i);
2815 pw.print(" uid: ");
2816 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002817 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2818 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002819 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002820 }
2821 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002822
Christopher Tateb49ceb32010-02-08 16:22:24 -08002823 pw.println("Ancestral packages: "
2824 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002825 if (mAncestralPackages != null) {
2826 for (String pkg : mAncestralPackages) {
2827 pw.println(" " + pkg);
2828 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002829 }
2830
Christopher Tate73e02522009-07-15 14:18:26 -07002831 pw.println("Ever backed up: " + mEverStoredApps.size());
2832 for (String pkg : mEverStoredApps) {
2833 pw.println(" " + pkg);
2834 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002835
2836 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002837 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002838 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002839 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002840 }
2841 }
Christopher Tate487529a2009-04-29 14:03:25 -07002842}