blob: f1e226eed8adb0c273f11c55101fa04dd9ee5ee5 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.RestoreSet;
27import android.app.backup.IBackupManager;
28import android.app.backup.IRestoreObserver;
29import android.app.backup.IRestoreSession;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070031import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.content.Context;
33import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070036import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070037import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080038import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070039import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070041import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080042import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070045import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080050import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070052import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070053import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070057import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070059import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080062import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070063
Christopher Tated55e18a2009-09-21 10:12:59 -070064import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070065import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070067import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070068
Christopher Tatecde87f42009-06-12 12:55:53 -070069import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070070import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080072import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070073import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070074import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070075import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040077import java.util.ArrayList;
78import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070079import java.util.HashSet;
80import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070081import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070082import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080083import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070084
85class BackupManagerService extends IBackupManager.Stub {
86 private static final String TAG = "BackupManagerService";
Chris Tate18580312010-10-19 11:22:03 -070087 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 Tatec7b31e32009-06-10 15:49:30 -0700110
111 // Timeout interval for deciding that a bind or clear-data has taken too long
112 static final long TIMEOUT_INTERVAL = 10 * 1000;
113
Christopher Tate44a27902010-01-27 17:15:49 -0800114 // Timeout intervals for agent backup & restore operations
115 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
116 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
117
Christopher Tate487529a2009-04-29 14:03:25 -0700118 private Context mContext;
119 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800120 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700121 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700122 private PowerManager mPowerManager;
123 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800124 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700125
Christopher Tate73e02522009-07-15 14:18:26 -0700126 boolean mEnabled; // access to this is synchronized on 'this'
127 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800128 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700129 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800130 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
131 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700132 PendingIntent mRunBackupIntent, mRunInitIntent;
133 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700134 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700135 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700137 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700138 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700139 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700140 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate181fafa2009-05-14 11:12:14 -0700142 BackupRequest(ApplicationInfo app, boolean isFull) {
143 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700144 fullBackup = isFull;
145 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700146
147 public String toString() {
148 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
149 }
Christopher Tate46758122009-05-06 11:22:00 -0700150 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400151 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700152 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700153 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700154
155 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700156 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700157
158 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700159 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700160
Christopher Tate043dadc2009-06-02 16:11:00 -0700161 // The thread performing the sequence of queued backups binds to each app's agent
162 // in succession. Bind notifications are asynchronously delivered through the
163 // Activity Manager; use this lock object to signal when a requested binding has
164 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700165 final Object mAgentConnectLock = new Object();
166 IBackupAgent mConnectedAgent;
167 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700168 volatile long mLastBackupPass;
169 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700170
Christopher Tate55f931a2009-09-29 17:17:34 -0700171 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700172 final Object mClearDataLock = new Object();
173 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700174
Christopher Tate91717492009-06-26 21:07:13 -0700175 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700176 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700177 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700178 String mCurrentTransport;
179 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800180 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700181
Christopher Tate2d449afe2010-03-29 19:14:24 -0700182 class RestoreGetSetsParams {
183 public IBackupTransport transport;
184 public ActiveRestoreSession session;
185 public IRestoreObserver observer;
186
187 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
188 IRestoreObserver _observer) {
189 transport = _transport;
190 session = _session;
191 observer = _observer;
192 }
193 }
194
Christopher Tate73e02522009-07-15 14:18:26 -0700195 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700196 public IBackupTransport transport;
197 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700198 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800199 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800200 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tatebbff7ed2010-10-29 12:57:04 -0700201 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800202
203 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tatebbff7ed2010-10-29 12:57:04 -0700204 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800205 transport = _transport;
206 observer = _obs;
207 token = _token;
208 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800209 pmToken = _pmToken;
Chris Tatebbff7ed2010-10-29 12:57:04 -0700210 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800211 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700212
Chris Tatebbff7ed2010-10-29 12:57:04 -0700213 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
214 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700215 transport = _transport;
216 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700217 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800218 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800219 pmToken = 0;
Chris Tatebbff7ed2010-10-29 12:57:04 -0700220 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700221 }
222 }
223
Christopher Tate73e02522009-07-15 14:18:26 -0700224 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700225 public IBackupTransport transport;
226 public PackageInfo packageInfo;
227
228 ClearParams(IBackupTransport _transport, PackageInfo _info) {
229 transport = _transport;
230 packageInfo = _info;
231 }
232 }
233
Christopher Tate44a27902010-01-27 17:15:49 -0800234 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
235 // token is the index of the entry in the pending-operations list.
236 static final int OP_PENDING = 0;
237 static final int OP_ACKNOWLEDGED = 1;
238 static final int OP_TIMEOUT = -1;
239
240 final SparseIntArray mCurrentOperations = new SparseIntArray();
241 final Object mCurrentOpLock = new Object();
242 final Random mTokenGenerator = new Random();
243
Christopher Tate5cb400b2009-06-25 16:03:14 -0700244 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700245 File mBaseStateDir;
246 File mDataDir;
247 File mJournalDir;
248 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700249
Christopher Tate84725812010-02-04 15:52:40 -0800250 // Keep a log of all the apps we've ever backed up, and what the
251 // dataset tokens are for both the current backup dataset and
252 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700253 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700254 HashSet<String> mEverStoredApps = new HashSet<String>();
255
Christopher Tateb49ceb32010-02-08 16:22:24 -0800256 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800257 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800258 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800259 long mAncestralToken = 0;
260 long mCurrentToken = 0;
261
Christopher Tate4cc86e12009-09-21 19:36:51 -0700262 // Persistently track the need to do a full init
263 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
264 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700265
Christopher Tate44a27902010-01-27 17:15:49 -0800266 // ----- Asynchronous backup/restore handler thread -----
267
268 private class BackupHandler extends Handler {
269 public BackupHandler(Looper looper) {
270 super(looper);
271 }
272
273 public void handleMessage(Message msg) {
274
275 switch (msg.what) {
276 case MSG_RUN_BACKUP:
277 {
278 mLastBackupPass = System.currentTimeMillis();
279 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
280
281 IBackupTransport transport = getTransport(mCurrentTransport);
282 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800284 mWakelock.release();
285 break;
286 }
287
288 // snapshot the pending-backup set and work on that
289 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800290 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800291 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800292 // Do we have any work to do? Construct the work queue
293 // then release the synchronization lock to actually run
294 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800295 if (mPendingBackups.size() > 0) {
296 for (BackupRequest b: mPendingBackups.values()) {
297 queue.add(b);
298 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800299 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800300 mPendingBackups.clear();
301
302 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800303 mJournal = null;
304
Christopher Tate44a27902010-01-27 17:15:49 -0800305 }
306 }
Christopher Tatec61da312010-02-05 10:41:27 -0800307
308 if (queue.size() > 0) {
309 // At this point, we have started a new journal file, and the old
310 // file identity is being passed to the backup processing thread.
311 // When it completes successfully, that old journal file will be
312 // deleted. If we crash prior to that, the old journal is parsed
313 // at next boot and the journaled requests fulfilled.
314 (new PerformBackupTask(transport, queue, oldJournal)).run();
315 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800316 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800317 mWakelock.release();
318 }
Christopher Tate44a27902010-01-27 17:15:49 -0800319 break;
320 }
321
322 case MSG_RUN_FULL_BACKUP:
323 break;
324
325 case MSG_RUN_RESTORE:
326 {
327 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800328 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800329 (new PerformRestoreTask(params.transport, params.observer,
Chris Tatebbff7ed2010-10-29 12:57:04 -0700330 params.token, params.pkgInfo, params.pmToken,
331 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800332 break;
333 }
334
335 case MSG_RUN_CLEAR:
336 {
337 ClearParams params = (ClearParams)msg.obj;
338 (new PerformClearTask(params.transport, params.packageInfo)).run();
339 break;
340 }
341
342 case MSG_RUN_INITIALIZE:
343 {
344 HashSet<String> queue;
345
346 // Snapshot the pending-init queue and work on that
347 synchronized (mQueueLock) {
348 queue = new HashSet<String>(mPendingInits);
349 mPendingInits.clear();
350 }
351
352 (new PerformInitializeTask(queue)).run();
353 break;
354 }
355
Christopher Tate2d449afe2010-03-29 19:14:24 -0700356 case MSG_RUN_GET_RESTORE_SETS:
357 {
358 // Like other async operations, this is entered with the wakelock held
359 RestoreSet[] sets = null;
360 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
361 try {
362 sets = params.transport.getAvailableRestoreSets();
363 // cache the result in the active session
364 synchronized (params.session) {
365 params.session.mRestoreSets = sets;
366 }
367 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
368 } catch (Exception e) {
369 Slog.e(TAG, "Error from transport getting set list");
370 } finally {
371 if (params.observer != null) {
372 try {
373 params.observer.restoreSetsAvailable(sets);
374 } catch (RemoteException re) {
375 Slog.e(TAG, "Unable to report listing to observer");
376 } catch (Exception e) {
377 Slog.e(TAG, "Restore observer threw", e);
378 }
379 }
380
381 mWakelock.release();
382 }
383 break;
384 }
385
Christopher Tate44a27902010-01-27 17:15:49 -0800386 case MSG_TIMEOUT:
387 {
388 synchronized (mCurrentOpLock) {
389 final int token = msg.arg1;
390 int state = mCurrentOperations.get(token, OP_TIMEOUT);
391 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800392 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800393 mCurrentOperations.put(token, OP_TIMEOUT);
394 }
395 mCurrentOpLock.notifyAll();
396 }
397 break;
398 }
399 }
400 }
401 }
402
403 // ----- Main service implementation -----
404
Christopher Tate487529a2009-04-29 14:03:25 -0700405 public BackupManagerService(Context context) {
406 mContext = context;
407 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700408 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700409 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700410
Christopher Tateb6787f22009-07-02 17:40:45 -0700411 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
412 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
413
Christopher Tate44a27902010-01-27 17:15:49 -0800414 mBackupManagerBinder = asInterface(asBinder());
415
416 // spin up the backup/restore handler thread
417 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
418 mHandlerThread.start();
419 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
420
Christopher Tate22b87872009-05-04 16:41:53 -0700421 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700422 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700423 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700424 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700425 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800426 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800427 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800428 // If Encrypted file systems is enabled or disabled, this call will return the
429 // correct directory.
430 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
431 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700432 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700433
Christopher Tate4cc86e12009-09-21 19:36:51 -0700434 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700435 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700436 IntentFilter filter = new IntentFilter();
437 filter.addAction(RUN_BACKUP_ACTION);
438 context.registerReceiver(mRunBackupReceiver, filter,
439 android.Manifest.permission.BACKUP, null);
440
441 mRunInitReceiver = new RunInitializeReceiver();
442 filter = new IntentFilter();
443 filter.addAction(RUN_INITIALIZE_ACTION);
444 context.registerReceiver(mRunInitReceiver, filter,
445 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700446
447 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700448 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
449 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
450
Christopher Tate4cc86e12009-09-21 19:36:51 -0700451 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
452 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
453 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
454
Christopher Tatecde87f42009-06-12 12:55:53 -0700455 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700456 mJournalDir = new File(mBaseStateDir, "pending");
457 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700458 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700459
Christopher Tate73e02522009-07-15 14:18:26 -0700460 // Set up the various sorts of package tracking we do
461 initPackageTracking();
462
Christopher Tateabce4e82009-06-18 18:35:32 -0700463 // Build our mapping of uid to backup client services. This implicitly
464 // schedules a backup pass on the Package Manager metadata the first
465 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700466 synchronized (mBackupParticipants) {
467 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700468 }
469
Dan Egnor87a02bc2009-06-17 02:30:10 -0700470 // Set up our transport options and initialize the default transport
471 // TODO: Have transports register themselves somehow?
472 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700473 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700474 ComponentName localName = new ComponentName(context, LocalTransport.class);
475 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700476
Christopher Tate91717492009-06-26 21:07:13 -0700477 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700478 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
479 Settings.Secure.BACKUP_TRANSPORT);
480 if ("".equals(mCurrentTransport)) {
481 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700482 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800483 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700484
485 // Attach to the Google backup transport. When this comes up, it will set
486 // itself as the current transport because we explicitly reset mCurrentTransport
487 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700488 ComponentName transportComponent = new ComponentName("com.google.android.backup",
489 "com.google.android.backup.BackupTransportService");
490 try {
491 // If there's something out there that is supposed to be the Google
492 // backup transport, make sure it's legitimately part of the OS build
493 // and not an app lying about its package name.
494 ApplicationInfo info = mPackageManager.getApplicationInfo(
495 transportComponent.getPackageName(), 0);
496 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
497 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
498 Intent intent = new Intent().setComponent(transportComponent);
499 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
500 } else {
501 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
502 }
503 } catch (PackageManager.NameNotFoundException nnf) {
504 // No such package? No binding.
505 if (DEBUG) Slog.v(TAG, "Google transport not present");
506 }
Christopher Tateaa088442009-06-16 18:25:46 -0700507
Christopher Tatecde87f42009-06-12 12:55:53 -0700508 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700509 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700510 parseLeftoverJournals();
511
Christopher Tateb6787f22009-07-02 17:40:45 -0700512 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700513 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700514
515 // Start the backup passes going
516 setBackupEnabled(areEnabled);
517 }
518
519 private class RunBackupReceiver extends BroadcastReceiver {
520 public void onReceive(Context context, Intent intent) {
521 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700522 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700523 if (mPendingInits.size() > 0) {
524 // If there are pending init operations, we process those
525 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800526 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700527 try {
528 mAlarmManager.cancel(mRunInitIntent);
529 mRunInitIntent.send();
530 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800531 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700532 // can't really do more than bail here
533 }
534 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800535 // Don't run backups now if we're disabled or not yet
536 // fully set up.
537 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800538 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700539
540 // Acquire the wakelock and pass it to the backup thread. it will
541 // be released once backup concludes.
542 mWakelock.acquire();
543
544 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
545 mBackupHandler.sendMessage(msg);
546 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800547 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700548 }
549 }
550 }
551 }
552 }
553 }
554
555 private class RunInitializeReceiver extends BroadcastReceiver {
556 public void onReceive(Context context, Intent intent) {
557 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
558 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800559 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700560
561 // Acquire the wakelock and pass it to the init thread. it will
562 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700563 mWakelock.acquire();
564
Christopher Tate4cc86e12009-09-21 19:36:51 -0700565 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700566 mBackupHandler.sendMessage(msg);
567 }
568 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700569 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700570 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700571
Christopher Tate73e02522009-07-15 14:18:26 -0700572 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800573 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700574
Christopher Tate84725812010-02-04 15:52:40 -0800575 // Remember our ancestral dataset
576 mTokenFile = new File(mBaseStateDir, "ancestral");
577 try {
578 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800579 int version = tf.readInt();
580 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
581 mAncestralToken = tf.readLong();
582 mCurrentToken = tf.readLong();
583
584 int numPackages = tf.readInt();
585 if (numPackages >= 0) {
586 mAncestralPackages = new HashSet<String>();
587 for (int i = 0; i < numPackages; i++) {
588 String pkgName = tf.readUTF();
589 mAncestralPackages.add(pkgName);
590 }
591 }
592 }
Christopher Tate1168baa2010-02-17 13:03:40 -0800593 } catch (FileNotFoundException fnf) {
594 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800595 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800596 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800597 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800598 }
599
Christopher Tatee97e8072009-07-15 16:45:50 -0700600 // Keep a log of what apps we've ever backed up. Because we might have
601 // rebooted in the middle of an operation that was removing something from
602 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700603 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700604 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700605
Christopher Tatee97e8072009-07-15 16:45:50 -0700606 // If we were in the middle of removing something from the ever-backed-up
607 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700608 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700609 if (tempProcessedFile.exists()) {
610 tempProcessedFile.delete();
611 }
612
Dan Egnor852f8e42009-09-30 11:20:45 -0700613 // If there are previous contents, parse them out then start a new
614 // file to continue the recordkeeping.
615 if (mEverStored.exists()) {
616 RandomAccessFile temp = null;
617 RandomAccessFile in = null;
618
619 try {
620 temp = new RandomAccessFile(tempProcessedFile, "rws");
621 in = new RandomAccessFile(mEverStored, "r");
622
623 while (true) {
624 PackageInfo info;
625 String pkg = in.readUTF();
626 try {
627 info = mPackageManager.getPackageInfo(pkg, 0);
628 mEverStoredApps.add(pkg);
629 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800630 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700631 } catch (NameNotFoundException e) {
632 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800633 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700634 }
635 }
636 } catch (EOFException e) {
637 // Once we've rewritten the backup history log, atomically replace the
638 // old one with the new one then reopen the file for continuing use.
639 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800640 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700641 }
642 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800643 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700644 } finally {
645 try { if (temp != null) temp.close(); } catch (IOException e) {}
646 try { if (in != null) in.close(); } catch (IOException e) {}
647 }
648 }
649
Christopher Tate73e02522009-07-15 14:18:26 -0700650 // Register for broadcasts about package install, etc., so we can
651 // update the provider list.
652 IntentFilter filter = new IntentFilter();
653 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
654 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
655 filter.addDataScheme("package");
656 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800657 // Register for events related to sdcard installation.
658 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800659 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
660 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800661 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700662 }
663
Christopher Tatecde87f42009-06-12 12:55:53 -0700664 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700665 for (File f : mJournalDir.listFiles()) {
666 if (mJournal == null || f.compareTo(mJournal) != 0) {
667 // This isn't the current journal, so it must be a leftover. Read
668 // out the package names mentioned there and schedule them for
669 // backup.
670 RandomAccessFile in = null;
671 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400672 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700673 in = new RandomAccessFile(f, "r");
674 while (true) {
675 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400676 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700677 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700678 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700679 } catch (EOFException e) {
680 // no more data; we're done
681 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700683 } finally {
684 // close/delete the file
685 try { if (in != null) in.close(); } catch (IOException e) {}
686 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700687 }
688 }
689 }
690 }
691
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692 // Maintain persistent state around whether need to do an initialize operation.
693 // Must be called with the queue lock held.
694 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800695 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700696 + " on transport " + transportName);
697 try {
698 IBackupTransport transport = getTransport(transportName);
699 String transportDirName = transport.transportDirName();
700 File stateDir = new File(mBaseStateDir, transportDirName);
701 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
702
703 if (isPending) {
704 // We need an init before we can proceed with sending backup data.
705 // Record that with an entry in our set of pending inits, as well as
706 // journaling it via creation of a sentinel file.
707 mPendingInits.add(transportName);
708 try {
709 (new FileOutputStream(initPendingFile)).close();
710 } catch (IOException ioe) {
711 // Something is badly wrong with our permissions; just try to move on
712 }
713 } else {
714 // No more initialization needed; wipe the journal and reset our state.
715 initPendingFile.delete();
716 mPendingInits.remove(transportName);
717 }
718 } catch (RemoteException e) {
719 // can't happen; the transport is local
720 }
721 }
722
Christopher Tated55e18a2009-09-21 10:12:59 -0700723 // Reset all of our bookkeeping, in response to having been told that
724 // the backend data has been wiped [due to idle expiry, for example],
725 // so we must re-upload all saved settings.
726 void resetBackupState(File stateFileDir) {
727 synchronized (mQueueLock) {
728 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700729 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700730 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700731
Christopher Tate84725812010-02-04 15:52:40 -0800732 mCurrentToken = 0;
733 writeRestoreTokens();
734
Christopher Tated55e18a2009-09-21 10:12:59 -0700735 // Remove all the state files
736 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700737 // ... but don't touch the needs-init sentinel
738 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
739 sf.delete();
740 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700741 }
742
743 // Enqueue a new backup of every participant
744 int N = mBackupParticipants.size();
745 for (int i=0; i<N; i++) {
746 int uid = mBackupParticipants.keyAt(i);
747 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
748 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700749 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700750 }
751 }
752 }
753 }
754
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800755 // Add a transport to our set of available backends. If 'transport' is null, this
756 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700757 private void registerTransport(String name, IBackupTransport transport) {
758 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800759 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800760 if (transport != null) {
761 mTransports.put(name, transport);
762 } else {
763 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800764 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800765 mCurrentTransport = null;
766 }
767 // Nothing further to do in the unregistration case
768 return;
769 }
Christopher Tate91717492009-06-26 21:07:13 -0700770 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700771
772 // If the init sentinel file exists, we need to be sure to perform the init
773 // as soon as practical. We also create the state directory at registration
774 // time to ensure it's present from the outset.
775 try {
776 String transportName = transport.transportDirName();
777 File stateDir = new File(mBaseStateDir, transportName);
778 stateDir.mkdirs();
779
780 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
781 if (initSentinel.exists()) {
782 synchronized (mQueueLock) {
783 mPendingInits.add(transportName);
784
785 // TODO: pick a better starting time than now + 1 minute
786 long delay = 1000 * 60; // one minute, in milliseconds
787 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
788 System.currentTimeMillis() + delay, mRunInitIntent);
789 }
790 }
791 } catch (RemoteException e) {
792 // can't happen, the transport is local
793 }
Christopher Tate91717492009-06-26 21:07:13 -0700794 }
795
Christopher Tate3799bc22009-05-06 16:13:56 -0700796 // ----- Track installation/removal of packages -----
797 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
798 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800799 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700800
Christopher Tate3799bc22009-05-06 16:13:56 -0700801 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800802 boolean replacing = false;
803 boolean added = false;
804 Bundle extras = intent.getExtras();
805 String pkgList[] = null;
806 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
807 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
808 Uri uri = intent.getData();
809 if (uri == null) {
810 return;
811 }
812 String pkgName = uri.getSchemeSpecificPart();
813 if (pkgName != null) {
814 pkgList = new String[] { pkgName };
815 }
816 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
817 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800818 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800819 added = true;
820 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800821 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800822 added = false;
823 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
824 }
825 if (pkgList == null || pkgList.length == 0) {
826 return;
827 }
828 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700829 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800830 for (String pkgName : pkgList) {
831 if (replacing) {
832 // The package was just upgraded
833 updatePackageParticipantsLocked(pkgName);
834 } else {
835 // The package was just added
836 addPackageParticipantsLocked(pkgName);
837 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700838 }
839 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800840 } else {
841 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700842 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
843 } else {
844 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800845 for (String pkgName : pkgList) {
846 removePackageParticipantsLocked(pkgName);
847 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700848 }
849 }
850 }
851 }
852 };
853
Dan Egnor87a02bc2009-06-17 02:30:10 -0700854 // ----- Track connection to GoogleBackupTransport service -----
855 ServiceConnection mGoogleConnection = new ServiceConnection() {
856 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700858 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700859 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700860 }
861
862 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700864 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700865 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700866 }
867 };
868
Christopher Tate181fafa2009-05-14 11:12:14 -0700869 // Add the backup agents in the given package to our set of known backup participants.
870 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700871 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700872 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800873 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700874 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700875 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700876 }
877
Christopher Tate181fafa2009-05-14 11:12:14 -0700878 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700879 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700880 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700882 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800883 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700884 + " uid=" + p.applicationInfo.uid
885 + " killAfterRestore="
886 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700887 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700888 }
889 }
890
Dan Egnorefe52642009-06-24 00:16:33 -0700891 for (PackageInfo pkg : targetPkgs) {
892 if (packageName == null || pkg.packageName.equals(packageName)) {
893 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700894 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700895 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700896 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700897 mBackupParticipants.put(uid, set);
898 }
Dan Egnorefe52642009-06-24 00:16:33 -0700899 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700900
901 // If we've never seen this app before, schedule a backup for it
902 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700904 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700905 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700906 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700907 }
Christopher Tate487529a2009-04-29 14:03:25 -0700908 }
909 }
910
Christopher Tate6785dd82009-06-18 15:58:25 -0700911 // Remove the given package's entry from our known active set. If
912 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700913 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800914 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700915 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700916 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700917 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700918 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700919 int flags = PackageManager.GET_SIGNATURES;
920 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700921 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700922 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700923 }
924 } else {
925 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700926 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700927 }
928 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700929 }
930
Joe Onorato8ad02812009-05-13 01:41:44 -0400931 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700932 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700933 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800934 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700935 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700936 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800937 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700938 }
939 }
Dan Egnorefe52642009-06-24 00:16:33 -0700940 for (PackageInfo pkg : agents) {
941 if (packageName == null || pkg.packageName.equals(packageName)) {
942 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700943 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700944 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700945 // Find the existing entry with the same package name, and remove it.
946 // We can't just remove(app) because the instances are different.
947 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700948 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700949 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700950 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700951 break;
952 }
953 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700954 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700955 mBackupParticipants.delete(uid);
956 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700957 }
958 }
959 }
960 }
961
Christopher Tate181fafa2009-05-14 11:12:14 -0700962 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700963 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700964 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700965 int flags = PackageManager.GET_SIGNATURES;
966 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
967 int N = packages.size();
968 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700969 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700970 try {
971 ApplicationInfo app = pkg.applicationInfo;
972 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800973 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700974 packages.remove(a);
975 }
976 else {
977 // we will need the shared library path, so look that up and store it here
978 app = mPackageManager.getApplicationInfo(pkg.packageName,
979 PackageManager.GET_SHARED_LIBRARY_FILES);
980 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
981 }
982 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700983 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700984 }
985 }
Dan Egnorefe52642009-06-24 00:16:33 -0700986 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700987 }
Christopher Tateaa088442009-06-16 18:25:46 -0700988
Christopher Tate3799bc22009-05-06 16:13:56 -0700989 // Reset the given package's known backup participants. Unlike add/remove, the update
990 // action cannot be passed a null package name.
991 void updatePackageParticipantsLocked(String packageName) {
992 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800993 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700994 return;
995 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800996 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700997
998 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700999 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001000 removePackageParticipantsLockedInner(packageName, allApps);
1001 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001002 }
1003
Christopher Tate84725812010-02-04 15:52:40 -08001004 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001005 // backed up at least once
1006 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001007 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1008
1009 synchronized (mEverStoredApps) {
1010 if (!mEverStoredApps.add(packageName)) return;
1011
1012 RandomAccessFile out = null;
1013 try {
1014 out = new RandomAccessFile(mEverStored, "rws");
1015 out.seek(out.length());
1016 out.writeUTF(packageName);
1017 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001018 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001019 } finally {
1020 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001021 }
1022 }
1023 }
1024
Christopher Tatee97e8072009-07-15 16:45:50 -07001025 // Remove our awareness of having ever backed up the given package
1026 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001027 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001028
Dan Egnor852f8e42009-09-30 11:20:45 -07001029 synchronized (mEverStoredApps) {
1030 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1031 // we'll recognize on initialization time that the package no longer
1032 // exists and fix it up then.
1033 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1034 RandomAccessFile known = null;
1035 try {
1036 known = new RandomAccessFile(tempKnownFile, "rws");
1037 mEverStoredApps.remove(packageName);
1038 for (String s : mEverStoredApps) {
1039 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001040 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001041 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001042 known.close();
1043 known = null;
1044 if (!tempKnownFile.renameTo(mEverStored)) {
1045 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1046 }
1047 } catch (IOException e) {
1048 // Bad: we couldn't create the new copy. For safety's sake we
1049 // abandon the whole process and remove all what's-backed-up
1050 // state entirely, meaning we'll force a backup pass for every
1051 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001052 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001053 mEverStoredApps.clear();
1054 tempKnownFile.delete();
1055 mEverStored.delete();
1056 } finally {
1057 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001058 }
1059 }
1060 }
1061
Christopher Tateb49ceb32010-02-08 16:22:24 -08001062 // Persistently record the current and ancestral backup tokens as well
1063 // as the set of packages with data [supposedly] available in the
1064 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001065 void writeRestoreTokens() {
1066 try {
1067 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001068
1069 // First, the version number of this record, for futureproofing
1070 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1071
1072 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001073 af.writeLong(mAncestralToken);
1074 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001075
1076 // Now write the set of ancestral packages
1077 if (mAncestralPackages == null) {
1078 af.writeInt(-1);
1079 } else {
1080 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001081 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001082 for (String pkgName : mAncestralPackages) {
1083 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001084 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001085 }
1086 }
Christopher Tate84725812010-02-04 15:52:40 -08001087 af.close();
1088 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001089 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001090 }
1091 }
1092
Dan Egnor87a02bc2009-06-17 02:30:10 -07001093 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001094 private IBackupTransport getTransport(String transportName) {
1095 synchronized (mTransports) {
1096 IBackupTransport transport = mTransports.get(transportName);
1097 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001098 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001099 }
1100 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001101 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001102 }
1103
Christopher Tatedf01dea2009-06-09 20:45:02 -07001104 // fire off a backup agent, blocking until it attaches or times out
1105 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1106 IBackupAgent agent = null;
1107 synchronized(mAgentConnectLock) {
1108 mConnecting = true;
1109 mConnectedAgent = null;
1110 try {
1111 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001112 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001113
1114 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001115 // only wait 10 seconds for the clear data to happen
1116 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1117 while (mConnecting && mConnectedAgent == null
1118 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001119 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001120 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001121 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001122 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001123 return null;
1124 }
1125 }
1126
1127 // if we timed out with no connect, abort and move on
1128 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001129 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001130 return null;
1131 }
1132 agent = mConnectedAgent;
1133 }
1134 } catch (RemoteException e) {
1135 // can't happen
1136 }
1137 }
1138 return agent;
1139 }
1140
Christopher Tatec7b31e32009-06-10 15:49:30 -07001141 // clear an application's data, blocking until the operation completes or times out
1142 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001143 // Don't wipe packages marked allowClearUserData=false
1144 try {
1145 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1146 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001147 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001148 + packageName);
1149 return;
1150 }
1151 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001152 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001153 return;
1154 }
1155
Christopher Tatec7b31e32009-06-10 15:49:30 -07001156 ClearDataObserver observer = new ClearDataObserver();
1157
1158 synchronized(mClearDataLock) {
1159 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001160 try {
1161 mActivityManager.clearApplicationUserData(packageName, observer);
1162 } catch (RemoteException e) {
1163 // can't happen because the activity manager is in this process
1164 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001165
1166 // only wait 10 seconds for the clear data to happen
1167 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1168 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1169 try {
1170 mClearDataLock.wait(5000);
1171 } catch (InterruptedException e) {
1172 // won't happen, but still.
1173 mClearingData = false;
1174 }
1175 }
1176 }
1177 }
1178
1179 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001180 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001181 synchronized(mClearDataLock) {
1182 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001183 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001184 }
1185 }
1186 }
1187
Christopher Tate1bb69062010-02-19 17:02:12 -08001188 // Get the restore-set token for the best-available restore set for this package:
1189 // the active set if possible, else the ancestral one. Returns zero if none available.
1190 long getAvailableRestoreToken(String packageName) {
1191 long token = mAncestralToken;
1192 synchronized (mQueueLock) {
1193 if (mEverStoredApps.contains(packageName)) {
1194 token = mCurrentToken;
1195 }
1196 }
1197 return token;
1198 }
1199
Christopher Tate44a27902010-01-27 17:15:49 -08001200 // -----
1201 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1202 boolean waitUntilOperationComplete(int token) {
1203 int finalState = OP_PENDING;
1204 synchronized (mCurrentOpLock) {
1205 try {
1206 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1207 try {
1208 mCurrentOpLock.wait();
1209 } catch (InterruptedException e) {}
1210 }
1211 } catch (IndexOutOfBoundsException e) {
1212 // the operation has been mysteriously cleared from our
1213 // bookkeeping -- consider this a success and ignore it.
1214 }
1215 }
1216 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001217 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001218 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001219 return finalState == OP_ACKNOWLEDGED;
1220 }
1221
1222 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001223 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001224 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001225 mCurrentOperations.put(token, OP_PENDING);
1226 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1227 mBackupHandler.sendMessageDelayed(msg, interval);
1228 }
1229
Christopher Tate043dadc2009-06-02 16:11:00 -07001230 // ----- Back up a set of applications via a worker thread -----
1231
Christopher Tate44a27902010-01-27 17:15:49 -08001232 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001233 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001234 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001235 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001236 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001237 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001238
Christopher Tate44a27902010-01-27 17:15:49 -08001239 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001240 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001241 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001242 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001243 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001244
1245 try {
1246 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1247 } catch (RemoteException e) {
1248 // can't happen; the transport is local
1249 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001250 }
1251
Christopher Tate043dadc2009-06-02 16:11:00 -07001252 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001253 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001254 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001255 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001256
Christopher Tate79588342009-06-30 16:11:49 -07001257 // Backups run at background priority
1258 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1259
Christopher Tate043dadc2009-06-02 16:11:00 -07001260 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001262
Dan Egnor852f8e42009-09-30 11:20:45 -07001263 // If we haven't stored package manager metadata yet, we must init the transport.
1264 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1265 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001266 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001267 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001268 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001269 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001270 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001271 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001272 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001273 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001274 }
Dan Egnor01445162009-09-21 17:04:05 -07001275 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001276
1277 // The package manager doesn't have a proper <application> etc, but since
1278 // it's running here in the system process we can just set up its agent
1279 // directly and use a synthetic BackupRequest. We always run this pass
1280 // because it's cheap and this way we guarantee that we don't get out of
1281 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001282 if (status == BackupConstants.TRANSPORT_OK) {
1283 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1284 mPackageManager, allAgentPackages());
1285 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1286 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1287 status = processOneBackup(pmRequest,
1288 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1289 }
Christopher Tate90967f42009-09-20 15:28:33 -07001290
Dan Egnor01445162009-09-21 17:04:05 -07001291 if (status == BackupConstants.TRANSPORT_OK) {
1292 // Now run all the backups in our queue
1293 status = doQueuedBackups(mTransport);
1294 }
1295
1296 if (status == BackupConstants.TRANSPORT_OK) {
1297 // Tell the transport to finish everything it has buffered
1298 status = mTransport.finishBackup();
1299 if (status == BackupConstants.TRANSPORT_OK) {
1300 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001301 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001302 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001303 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001304 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001305 }
1306 }
1307
Dan Egnor01445162009-09-21 17:04:05 -07001308 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001309 // The backend reports that our dataset has been wiped. We need to
1310 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001311 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001312 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001313 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001314 }
1315 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001316 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001317 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001318 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001319 // If everything actually went through and this is the first time we've
1320 // done a backup, we can now record what the current backup dataset token
1321 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001322 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001323 try {
1324 mCurrentToken = mTransport.getCurrentRestoreSet();
1325 } catch (RemoteException e) { /* cannot happen */ }
1326 writeRestoreTokens();
1327 }
1328
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001329 // If things went wrong, we need to re-stage the apps we had expected
1330 // to be backing up in this pass. This journals the package names in
1331 // the current active pending-backup file, not in the we are holding
1332 // here in mJournal.
1333 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001335 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001336 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001337 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001338
1339 // We also want to reset the backup schedule based on whatever
1340 // the transport suggests by way of retry/backoff time.
1341 try {
1342 startBackupAlarmsLocked(mTransport.requestBackupTime());
1343 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001344 }
1345
1346 // Either backup was successful, in which case we of course do not need
1347 // this pass's journal any more; or it failed, in which case we just
1348 // re-enqueued all of these packages in the current active journal.
1349 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001350 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001351 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001352 }
1353
Christopher Tatec2af5d32010-02-02 15:18:58 -08001354 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001355 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001356 backupNow();
1357 }
1358
Dan Egnorbb9001c2009-07-27 12:20:13 -07001359 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001360 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001361 }
1362
Dan Egnor01445162009-09-21 17:04:05 -07001363 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001364 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001365 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001366
1367 IBackupAgent agent = null;
1368 int mode = (request.fullBackup)
1369 ? IApplicationThread.BACKUP_MODE_FULL
1370 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1371 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001372 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001373 agent = bindToAgentSynchronous(request.appInfo, mode);
1374 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001375 int result = processOneBackup(request, agent, transport);
1376 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001377 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 } catch (SecurityException ex) {
1379 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001380 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001381 } finally {
1382 try { // unbind even on timeout, just in case
1383 mActivityManager.unbindBackupAgent(request.appInfo);
1384 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001385 }
1386 }
Dan Egnor01445162009-09-21 17:04:05 -07001387
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001388 mWakelock.setWorkSource(null);
1389
Dan Egnor01445162009-09-21 17:04:05 -07001390 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001391 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001392
Dan Egnor01445162009-09-21 17:04:05 -07001393 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1394 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001395 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001397
Dan Egnorbb9001c2009-07-27 12:20:13 -07001398 File savedStateName = new File(mStateDir, packageName);
1399 File backupDataName = new File(mDataDir, packageName + ".data");
1400 File newStateName = new File(mStateDir, packageName + ".new");
1401
1402 ParcelFileDescriptor savedState = null;
1403 ParcelFileDescriptor backupData = null;
1404 ParcelFileDescriptor newState = null;
1405
1406 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001407 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001408 try {
1409 // Look up the package info & signatures. This is first so that if it
1410 // throws an exception, there's no file setup yet that would need to
1411 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001412 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1413 // The metadata 'package' is synthetic
1414 packInfo = new PackageInfo();
1415 packInfo.packageName = packageName;
1416 } else {
1417 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001418 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001419 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001420
Christopher Tatec7b31e32009-06-10 15:49:30 -07001421 // In a full backup, we pass a null ParcelFileDescriptor as
1422 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001423 if (!request.fullBackup) {
1424 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001425 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001426 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1427 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001428
Dan Egnorbb9001c2009-07-27 12:20:13 -07001429 backupData = ParcelFileDescriptor.open(backupDataName,
1430 ParcelFileDescriptor.MODE_READ_WRITE |
1431 ParcelFileDescriptor.MODE_CREATE |
1432 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001433
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434 newState = ParcelFileDescriptor.open(newStateName,
1435 ParcelFileDescriptor.MODE_READ_WRITE |
1436 ParcelFileDescriptor.MODE_CREATE |
1437 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001438
Christopher Tate44a27902010-01-27 17:15:49 -08001439 // Initiate the target's backup pass
1440 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1441 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1442 boolean success = waitUntilOperationComplete(token);
1443
1444 if (!success) {
1445 // timeout -- bail out into the failed-transaction logic
1446 throw new RuntimeException("Backup timeout");
1447 }
1448
Dan Egnorbb9001c2009-07-27 12:20:13 -07001449 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001450 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001451 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001452 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001454 backupDataName.delete();
1455 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001456 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001457 } finally {
1458 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1459 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1460 try { if (newState != null) newState.close(); } catch (IOException e) {}
1461 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001462 synchronized (mCurrentOpLock) {
1463 mCurrentOperations.clear();
1464 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001465 }
1466
1467 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001468 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001469 try {
1470 int size = (int) backupDataName.length();
1471 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001472 if (result == BackupConstants.TRANSPORT_OK) {
1473 backupData = ParcelFileDescriptor.open(backupDataName,
1474 ParcelFileDescriptor.MODE_READ_ONLY);
1475 result = transport.performBackup(packInfo, backupData);
1476 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477
Dan Egnor83861e72009-09-17 16:17:55 -07001478 // TODO - We call finishBackup() for each application backed up, because
1479 // we need to know now whether it succeeded or failed. Instead, we should
1480 // hold off on finishBackup() until the end, which implies holding off on
1481 // renaming *all* the output state files (see below) until that happens.
1482
Dan Egnor01445162009-09-21 17:04:05 -07001483 if (result == BackupConstants.TRANSPORT_OK) {
1484 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001485 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001486 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001487 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001488 }
1489
1490 // After successful transport, delete the now-stale data
1491 // and juggle the files so that next time we supply the agent
1492 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001493 if (result == BackupConstants.TRANSPORT_OK) {
1494 backupDataName.delete();
1495 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001497 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001498 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001499 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001500 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001502 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001503 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001504 } finally {
1505 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001506 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001507
Dan Egnor01445162009-09-21 17:04:05 -07001508 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001509 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001510 }
1511
Christopher Tatedf01dea2009-06-09 20:45:02 -07001512
1513 // ----- Restore handling -----
1514
Christopher Tate78dd4a72009-11-04 11:49:08 -08001515 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1516 // If the target resides on the system partition, we allow it to restore
1517 // data from the like-named package in a restore set even if the signatures
1518 // do not match. (Unlike general applications, those flashed to the system
1519 // partition will be signed with the device's platform certificate, so on
1520 // different phones the same system app will have different signatures.)
1521 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001523 return true;
1524 }
1525
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001526 // Allow unsigned apps, but not signed on one device and unsigned on the other
1527 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001528 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001530 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001531 if ((storedSigs == null || storedSigs.length == 0)
1532 && (deviceSigs == null || deviceSigs.length == 0)) {
1533 return true;
1534 }
1535 if (storedSigs == null || deviceSigs == null) {
1536 return false;
1537 }
1538
Christopher Tateabce4e82009-06-18 18:35:32 -07001539 // !!! TODO: this demands that every stored signature match one
1540 // that is present on device, and does not demand the converse.
1541 // Is this this right policy?
1542 int nStored = storedSigs.length;
1543 int nDevice = deviceSigs.length;
1544
1545 for (int i=0; i < nStored; i++) {
1546 boolean match = false;
1547 for (int j=0; j < nDevice; j++) {
1548 if (storedSigs[i].equals(deviceSigs[j])) {
1549 match = true;
1550 break;
1551 }
1552 }
1553 if (!match) {
1554 return false;
1555 }
1556 }
1557 return true;
1558 }
1559
Christopher Tate44a27902010-01-27 17:15:49 -08001560 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001561 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001562 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001563 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001564 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001565 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001566 private int mPmToken;
Chris Tatebbff7ed2010-10-29 12:57:04 -07001567 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001568
Christopher Tate5cbbf562009-06-22 16:44:51 -07001569 class RestoreRequest {
1570 public PackageInfo app;
1571 public int storedAppVersion;
1572
1573 RestoreRequest(PackageInfo _app, int _version) {
1574 app = _app;
1575 storedAppVersion = _version;
1576 }
1577 }
1578
Christopher Tate44a27902010-01-27 17:15:49 -08001579 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tatebbff7ed2010-10-29 12:57:04 -07001580 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1581 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001582 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001583 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001584 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001585 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001586 mPmToken = pmToken;
Chris Tatebbff7ed2010-10-29 12:57:04 -07001587 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001588
1589 try {
1590 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1591 } catch (RemoteException e) {
1592 // can't happen; the transport is local
1593 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001594 }
1595
Christopher Tatedf01dea2009-06-09 20:45:02 -07001596 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001597 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001598 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001599 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001600 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001601
Christopher Tateb49ceb32010-02-08 16:22:24 -08001602 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001603 int error = -1; // assume error
1604
Dan Egnorefe52642009-06-24 00:16:33 -07001605 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001606 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001607 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001609
Dan Egnorefe52642009-06-24 00:16:33 -07001610 // Get the list of all packages which have backup enabled.
1611 // (Include the Package Manager metadata pseudo-package first.)
1612 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1613 PackageInfo omPackage = new PackageInfo();
1614 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1615 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001616
Dan Egnorefe52642009-06-24 00:16:33 -07001617 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001618 if (mTargetPackage == null) {
1619 restorePackages.addAll(agentPackages);
1620 } else {
1621 // Just one package to attempt restore of
1622 restorePackages.add(mTargetPackage);
1623 }
Dan Egnorefe52642009-06-24 00:16:33 -07001624
Christopher Tate7d562ec2009-06-25 18:03:43 -07001625 // let the observer know that we're running
1626 if (mObserver != null) {
1627 try {
1628 // !!! TODO: get an actual count from the transport after
1629 // its startRestore() runs?
1630 mObserver.restoreStarting(restorePackages.size());
1631 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001632 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001633 mObserver = null;
1634 }
1635 }
1636
Dan Egnor01445162009-09-21 17:04:05 -07001637 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1638 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001639 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001640 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001641 return;
1642 }
1643
1644 String packageName = mTransport.nextRestorePackage();
1645 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001646 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001647 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001648 return;
1649 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001651 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001652 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001653 return;
1654 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001655 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001656 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001657 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001658 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001659 return;
1660 }
1661
1662 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001663 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001664 mPackageManager, agentPackages);
Chris Tatebbff7ed2010-10-29 12:57:04 -07001665 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
1666 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07001667
Christopher Tate8c032472009-07-02 14:28:47 -07001668 // Verify that the backup set includes metadata. If not, we can't do
1669 // signature/version verification etc, so we simply do not proceed with
1670 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001671 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001672 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001673 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001674 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001675 return;
1676 }
1677
Christopher Tate7d562ec2009-06-25 18:03:43 -07001678 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001679 for (;;) {
1680 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001681
Dan Egnorefe52642009-06-24 00:16:33 -07001682 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001683 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001684 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001685 return;
1686 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001687 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001688 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001689 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001690
Christopher Tate7d562ec2009-06-25 18:03:43 -07001691 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001692 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001693 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001694 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001695 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001696 mObserver = null;
1697 }
1698 }
1699
Dan Egnorefe52642009-06-24 00:16:33 -07001700 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1701 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001702 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001703 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001704 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001705 continue;
1706 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001707
Dan Egnorbb9001c2009-07-27 12:20:13 -07001708 PackageInfo packageInfo;
1709 try {
1710 int flags = PackageManager.GET_SIGNATURES;
1711 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1712 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001713 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001714 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001715 "Package missing on device");
1716 continue;
1717 }
1718
Dan Egnorefe52642009-06-24 00:16:33 -07001719 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001720 // Data is from a "newer" version of the app than we have currently
1721 // installed. If the app has not declared that it is prepared to
1722 // handle this case, we do not attempt the restore.
1723 if ((packageInfo.applicationInfo.flags
1724 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1725 String message = "Version " + metaInfo.versionCode
1726 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001727 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001728 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1729 packageName, message);
1730 continue;
1731 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001732 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001733 + " > installed " + packageInfo.versionCode
1734 + " but restoreAnyVersion");
1735 }
Dan Egnorefe52642009-06-24 00:16:33 -07001736 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001737
Christopher Tate78dd4a72009-11-04 11:49:08 -08001738 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001739 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001740 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001741 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001742 continue;
1743 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001744
Joe Onorato8a9b2202010-02-26 18:56:32 -08001745 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001746 + " restore version [" + metaInfo.versionCode
1747 + "] is compatible with installed version ["
1748 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001749
Christopher Tate3de55bc2010-03-12 17:28:08 -08001750 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001751 IBackupAgent agent = bindToAgentSynchronous(
1752 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001753 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001754 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001755 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001756 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001757 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001758 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001759 }
1760
Christopher Tate5e1ab332009-09-01 20:32:49 -07001761 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001762 try {
Chris Tatebbff7ed2010-10-29 12:57:04 -07001763 processOneRestore(packageInfo, metaInfo.versionCode, agent,
1764 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001765 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001766 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001767 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001768 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001769
1770 // The agent was probably running with a stub Application object,
1771 // which isn't a valid run mode for the main app logic. Shut
1772 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001773 // usual full initialization. Note that this is only done for
1774 // full-system restores: when a single app has requested a restore,
1775 // it is explicitly not killed following that operation.
1776 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001777 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001778 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001779 + packageInfo.applicationInfo.processName);
1780 mActivityManager.killApplicationProcess(
1781 packageInfo.applicationInfo.processName,
1782 packageInfo.applicationInfo.uid);
1783 }
Dan Egnorefe52642009-06-24 00:16:33 -07001784 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001785 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001786
1787 // if we get this far, report success to the observer
1788 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001789 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001790 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001791 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001792 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001793 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001794 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001795
Dan Egnorefe52642009-06-24 00:16:33 -07001796 try {
1797 mTransport.finishRestore();
1798 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001799 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001800 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001801
1802 if (mObserver != null) {
1803 try {
1804 mObserver.restoreFinished(error);
1805 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001806 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001807 }
1808 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001809
Christopher Tate84725812010-02-04 15:52:40 -08001810 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001811 // ancestral dataset, as well as the set of apps that are possibly
1812 // restoreable from the dataset
1813 if (mTargetPackage == null && pmAgent != null) {
1814 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001815 mAncestralToken = mToken;
1816 writeRestoreTokens();
1817 }
1818
Christopher Tate1bb69062010-02-19 17:02:12 -08001819 // We must under all circumstances tell the Package Manager to
1820 // proceed with install notifications if it's waiting for us.
1821 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001822 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001823 try {
1824 mPackageManagerBinder.finishPackageInstall(mPmToken);
1825 } catch (RemoteException e) { /* can't happen */ }
1826 }
1827
Christopher Tateb6787f22009-07-02 17:40:45 -07001828 // done; we can finally release the wakelock
1829 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001830 }
1831 }
1832
Dan Egnorefe52642009-06-24 00:16:33 -07001833 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tatebbff7ed2010-10-29 12:57:04 -07001834 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
1835 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001836 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001837 final String packageName = app.packageName;
1838
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001840
Christopher Tatec7b31e32009-06-10 15:49:30 -07001841 // !!! TODO: get the dirs from the transport
1842 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001843 File newStateName = new File(mStateDir, packageName + ".new");
1844 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001845
Dan Egnorbb9001c2009-07-27 12:20:13 -07001846 ParcelFileDescriptor backupData = null;
1847 ParcelFileDescriptor newState = null;
1848
Christopher Tate44a27902010-01-27 17:15:49 -08001849 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001850 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001851 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001852 backupData = ParcelFileDescriptor.open(backupDataName,
1853 ParcelFileDescriptor.MODE_READ_WRITE |
1854 ParcelFileDescriptor.MODE_CREATE |
1855 ParcelFileDescriptor.MODE_TRUNCATE);
1856
Dan Egnor01445162009-09-21 17:04:05 -07001857 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001858 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001859 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001860 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001861 }
1862
1863 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001864 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001865 backupData = ParcelFileDescriptor.open(backupDataName,
1866 ParcelFileDescriptor.MODE_READ_ONLY);
1867
Dan Egnorbb9001c2009-07-27 12:20:13 -07001868 newState = ParcelFileDescriptor.open(newStateName,
1869 ParcelFileDescriptor.MODE_READ_WRITE |
1870 ParcelFileDescriptor.MODE_CREATE |
1871 ParcelFileDescriptor.MODE_TRUNCATE);
1872
Christopher Tate44a27902010-01-27 17:15:49 -08001873 // Kick off the restore, checking for hung agents
1874 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1875 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1876 boolean success = waitUntilOperationComplete(token);
1877
1878 if (!success) {
1879 throw new RuntimeException("restore timeout");
1880 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001881
1882 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001883 //
1884 // !!! TODO: the restored data should be migrated on the server
1885 // side into the current dataset. In that case the new state file
1886 // we just created would reflect the data already extant in the
1887 // backend, so there'd be nothing more to do. Until that happens,
1888 // however, we need to make sure that we record the data to the
1889 // current backend dataset. (Yes, this means shipping the data over
1890 // the wire in both directions. That's bad, but consistency comes
1891 // first, then efficiency.) Once we introduce server-side data
1892 // migration to the newly-restored device's dataset, we will change
1893 // the following from a discard of the newly-written state to the
1894 // "correct" operation of renaming into the canonical state blob.
1895 newStateName.delete(); // TODO: remove; see above comment
1896 //newStateName.renameTo(savedStateName); // TODO: replace with this
1897
Dan Egnorbb9001c2009-07-27 12:20:13 -07001898 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001899 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001900 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001901 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001902 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001903
Christopher Tate96733042009-07-20 14:49:13 -07001904 // If the agent fails restore, it might have put the app's data
1905 // into an incoherent state. For consistency we wipe its data
1906 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001907 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001908 } finally {
1909 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001910 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1911 try { if (newState != null) newState.close(); } catch (IOException e) {}
1912 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001913 mCurrentOperations.delete(token);
Chris Tatebbff7ed2010-10-29 12:57:04 -07001914
1915 // If we know a priori that we'll need to perform a full post-restore backup
1916 // pass, clear the new state file data. This means we're discarding work that
1917 // was just done by the app's agent, but this way the agent doesn't need to
1918 // take any special action based on global device state.
1919 if (needFullBackup) {
1920 newStateName.delete();
1921 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001922 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001923 }
1924 }
1925
Christopher Tate44a27902010-01-27 17:15:49 -08001926 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001927 IBackupTransport mTransport;
1928 PackageInfo mPackage;
1929
Christopher Tate44a27902010-01-27 17:15:49 -08001930 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001931 mTransport = transport;
1932 mPackage = packageInfo;
1933 }
1934
Christopher Tateee0e78a2009-07-02 11:17:03 -07001935 public void run() {
1936 try {
1937 // Clear the on-device backup state to ensure a full backup next time
1938 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1939 File stateFile = new File(stateDir, mPackage.packageName);
1940 stateFile.delete();
1941
1942 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001943 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001944 mTransport.clearBackupData(mPackage);
1945 } catch (RemoteException e) {
1946 // can't happen; the transport is local
1947 } finally {
1948 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001949 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001950 mTransport.finishBackup();
1951 } catch (RemoteException e) {
1952 // can't happen; the transport is local
1953 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001954
1955 // Last but not least, release the cpu
1956 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001957 }
1958 }
1959 }
1960
Christopher Tate44a27902010-01-27 17:15:49 -08001961 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001962 HashSet<String> mQueue;
1963
Christopher Tate44a27902010-01-27 17:15:49 -08001964 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001965 mQueue = transportNames;
1966 }
1967
Christopher Tate4cc86e12009-09-21 19:36:51 -07001968 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001969 try {
1970 for (String transportName : mQueue) {
1971 IBackupTransport transport = getTransport(transportName);
1972 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001973 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001974 continue;
1975 }
1976
Joe Onorato8a9b2202010-02-26 18:56:32 -08001977 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001978 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001979 long startRealtime = SystemClock.elapsedRealtime();
1980 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001981
Christopher Tate4cc86e12009-09-21 19:36:51 -07001982 if (status == BackupConstants.TRANSPORT_OK) {
1983 status = transport.finishBackup();
1984 }
1985
1986 // Okay, the wipe really happened. Clean up our local bookkeeping.
1987 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001988 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001989 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001990 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001991 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001992 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001993 synchronized (mQueueLock) {
1994 recordInitPendingLocked(false, transportName);
1995 }
Dan Egnor726247c2009-09-29 19:12:31 -07001996 } else {
1997 // If this didn't work, requeue this one and try again
1998 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08001999 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002000 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002001 synchronized (mQueueLock) {
2002 recordInitPendingLocked(true, transportName);
2003 }
2004 // do this via another alarm to make sure of the wakelock states
2005 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002006 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002007 + transportName + " resched in " + delay);
2008 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2009 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002010 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002011 }
2012 } catch (RemoteException e) {
2013 // can't happen; the transports are local
2014 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002015 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002016 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002017 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002018 mWakelock.release();
2019 }
2020 }
2021 }
2022
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002023 private void dataChangedImpl(String packageName) {
2024 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2025 dataChangedImpl(packageName, targets);
2026 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002027
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002028 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002029 // Record that we need a backup pass for the caller. Since multiple callers
2030 // may share a uid, we need to note all candidates within that uid and schedule
2031 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002032 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002033
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002034 if (targets == null) {
2035 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2036 + " uid=" + Binder.getCallingUid());
2037 return;
2038 }
2039
2040 synchronized (mQueueLock) {
2041 // Note that this client has made data changes that need to be backed up
2042 for (ApplicationInfo app : targets) {
2043 // validate the caller-supplied package name against the known set of
2044 // packages associated with this uid
2045 if (app.packageName.equals(packageName)) {
2046 // Add the caller to the set of pending backups. If there is
2047 // one already there, then overwrite it, but no harm done.
2048 BackupRequest req = new BackupRequest(app, false);
2049 if (mPendingBackups.put(app, req) == null) {
2050 // Journal this request in case of crash. The put()
2051 // operation returned null when this package was not already
2052 // in the set; we want to avoid touching the disk redundantly.
2053 writeToJournalLocked(packageName);
2054
2055 if (DEBUG) {
2056 int numKeys = mPendingBackups.size();
2057 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2058 for (BackupRequest b : mPendingBackups.values()) {
2059 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2060 }
2061 }
2062 }
2063 }
2064 }
2065 }
2066 }
2067
2068 // Note: packageName is currently unused, but may be in the future
2069 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002070 // If the caller does not hold the BACKUP permission, it can only request a
2071 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002072 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002073 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002074 synchronized (mBackupParticipants) {
2075 return mBackupParticipants.get(Binder.getCallingUid());
2076 }
2077 }
2078
2079 // a caller with full permission can ask to back up any participating app
2080 // !!! TODO: allow backup of ANY app?
2081 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2082 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002083 int N = mBackupParticipants.size();
2084 for (int i = 0; i < N; i++) {
2085 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2086 if (s != null) {
2087 targets.addAll(s);
2088 }
2089 }
2090 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002091 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002092 }
Christopher Tate46758122009-05-06 11:22:00 -07002093
Christopher Tatecde87f42009-06-12 12:55:53 -07002094 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002095 RandomAccessFile out = null;
2096 try {
2097 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2098 out = new RandomAccessFile(mJournal, "rws");
2099 out.seek(out.length());
2100 out.writeUTF(str);
2101 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002102 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002103 mJournal = null;
2104 } finally {
2105 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002106 }
2107 }
2108
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002109 // ----- IBackupManager binder interface -----
2110
2111 public void dataChanged(final String packageName) {
2112 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2113 if (targets == null) {
2114 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2115 + " uid=" + Binder.getCallingUid());
2116 return;
2117 }
2118
2119 mBackupHandler.post(new Runnable() {
2120 public void run() {
2121 dataChangedImpl(packageName, targets);
2122 }
2123 });
2124 }
2125
Christopher Tateee0e78a2009-07-02 11:17:03 -07002126 // Clear the given package's backup data from the current transport
2127 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002128 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002129 PackageInfo info;
2130 try {
2131 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2132 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002133 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002134 return;
2135 }
2136
2137 // If the caller does not hold the BACKUP permission, it can only request a
2138 // wipe of its own backed-up data.
2139 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002140 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002141 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2142 apps = mBackupParticipants.get(Binder.getCallingUid());
2143 } else {
2144 // a caller with full permission can ask to back up any participating app
2145 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002146 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002147 apps = new HashSet<ApplicationInfo>();
2148 int N = mBackupParticipants.size();
2149 for (int i = 0; i < N; i++) {
2150 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2151 if (s != null) {
2152 apps.addAll(s);
2153 }
2154 }
2155 }
2156
2157 // now find the given package in the set of candidate apps
2158 for (ApplicationInfo app : apps) {
2159 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002160 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002161 // found it; fire off the clear request
2162 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002163 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002164 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002165 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2166 new ClearParams(getTransport(mCurrentTransport), info));
2167 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002168 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002169 }
2170 break;
2171 }
2172 }
2173 }
2174
Christopher Tateace7f092009-06-15 18:07:25 -07002175 // Run a backup pass immediately for any applications that have declared
2176 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002177 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002179
Joe Onorato8a9b2202010-02-26 18:56:32 -08002180 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002181 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002182 // Because the alarms we are using can jitter, and we want an *immediate*
2183 // backup pass to happen, we restart the timer beginning with "next time,"
2184 // then manually fire the backup trigger intent ourselves.
2185 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002186 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002187 mRunBackupIntent.send();
2188 } catch (PendingIntent.CanceledException e) {
2189 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002190 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002191 }
Christopher Tate46758122009-05-06 11:22:00 -07002192 }
2193 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002194
Christopher Tate8031a3d2009-07-06 16:36:05 -07002195 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002196 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002197 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2198 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002199
Joe Onorato8a9b2202010-02-26 18:56:32 -08002200 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002201
Christopher Tate6ef58a12009-06-29 14:56:28 -07002202 boolean wasEnabled = mEnabled;
2203 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002204 Settings.Secure.putInt(mContext.getContentResolver(),
2205 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002206 mEnabled = enable;
2207 }
2208
Christopher Tate49401dd2009-07-01 12:34:29 -07002209 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002210 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002211 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002212 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002213 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002214 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002215 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002216
Christopher Tateb6787f22009-07-02 17:40:45 -07002217 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002218
2219 // This also constitutes an opt-out, so we wipe any data for
2220 // this device from the backend. We start that process with
2221 // an alarm in order to guarantee wakelock states.
2222 if (wasEnabled && mProvisioned) {
2223 // NOTE: we currently flush every registered transport, not just
2224 // the currently-active one.
2225 HashSet<String> allTransports;
2226 synchronized (mTransports) {
2227 allTransports = new HashSet<String>(mTransports.keySet());
2228 }
2229 // build the set of transports for which we are posting an init
2230 for (String transport : allTransports) {
2231 recordInitPendingLocked(true, transport);
2232 }
2233 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2234 mRunInitIntent);
2235 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002236 }
2237 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002238 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002239
Christopher Tatecce9da52010-02-03 15:11:15 -08002240 // Enable/disable automatic restore of app data at install time
2241 public void setAutoRestore(boolean doAutoRestore) {
2242 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2243 "setBackupEnabled");
2244
Joe Onorato8a9b2202010-02-26 18:56:32 -08002245 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002246
2247 synchronized (this) {
2248 Settings.Secure.putInt(mContext.getContentResolver(),
2249 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2250 mAutoRestore = doAutoRestore;
2251 }
2252 }
2253
Christopher Tate8031a3d2009-07-06 16:36:05 -07002254 // Mark the backup service as having been provisioned
2255 public void setBackupProvisioned(boolean available) {
2256 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2257 "setBackupProvisioned");
2258
2259 boolean wasProvisioned = mProvisioned;
2260 synchronized (this) {
2261 Settings.Secure.putInt(mContext.getContentResolver(),
2262 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2263 mProvisioned = available;
2264 }
2265
2266 synchronized (mQueueLock) {
2267 if (available && !wasProvisioned && mEnabled) {
2268 // we're now good to go, so start the backup alarms
2269 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2270 } else if (!available) {
2271 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002272 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002273 mAlarmManager.cancel(mRunBackupIntent);
2274 }
2275 }
2276 }
2277
2278 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002279 // We used to use setInexactRepeating(), but that may be linked to
2280 // backups running at :00 more often than not, creating load spikes.
2281 // Schedule at an exact time for now, and also add a bit of "fuzz".
2282
2283 Random random = new Random();
2284 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2285 random.nextInt(FUZZ_MILLIS);
2286 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2287 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002288 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002289 }
2290
Christopher Tate6ef58a12009-06-29 14:56:28 -07002291 // Report whether the backup mechanism is currently enabled
2292 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002294 return mEnabled; // no need to synchronize just to read it
2295 }
2296
Christopher Tate91717492009-06-26 21:07:13 -07002297 // Report the name of the currently active transport
2298 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002299 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002300 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002301 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002302 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002303 }
2304
Christopher Tate91717492009-06-26 21:07:13 -07002305 // Report all known, available backup transports
2306 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002308
Christopher Tate91717492009-06-26 21:07:13 -07002309 String[] list = null;
2310 ArrayList<String> known = new ArrayList<String>();
2311 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2312 if (entry.getValue() != null) {
2313 known.add(entry.getKey());
2314 }
2315 }
2316
2317 if (known.size() > 0) {
2318 list = new String[known.size()];
2319 known.toArray(list);
2320 }
2321 return list;
2322 }
2323
2324 // Select which transport to use for the next backup operation. If the given
2325 // name is not one of the available transports, no action is taken and the method
2326 // returns null.
2327 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002329
2330 synchronized (mTransports) {
2331 String prevTransport = null;
2332 if (mTransports.get(transport) != null) {
2333 prevTransport = mCurrentTransport;
2334 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002335 Settings.Secure.putString(mContext.getContentResolver(),
2336 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002337 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002338 + " returning " + prevTransport);
2339 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002340 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002341 }
2342 return prevTransport;
2343 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002344 }
2345
2346 // Callback: a requested backup agent has been instantiated. This should only
2347 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002348 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002349 synchronized(mAgentConnectLock) {
2350 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002351 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002352 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2353 mConnectedAgent = agent;
2354 mConnecting = false;
2355 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002356 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002357 + " claiming agent connected");
2358 }
2359 mAgentConnectLock.notifyAll();
2360 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002361 }
2362
2363 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2364 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002365 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002366 public void agentDisconnected(String packageName) {
2367 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002368 synchronized(mAgentConnectLock) {
2369 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2370 mConnectedAgent = null;
2371 mConnecting = false;
2372 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002373 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002374 + " claiming agent disconnected");
2375 }
2376 mAgentConnectLock.notifyAll();
2377 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002378 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002379
Christopher Tate1bb69062010-02-19 17:02:12 -08002380 // An application being installed will need a restore pass, then the Package Manager
2381 // will need to be told when the restore is finished.
2382 public void restoreAtInstall(String packageName, int token) {
2383 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002384 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002385 + " attemping install-time restore");
2386 return;
2387 }
2388
2389 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002390 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002391 + " token=" + Integer.toHexString(token));
2392
Christopher Tatef0872722010-02-25 15:22:48 -08002393 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002394 // okay, we're going to attempt a restore of this package from this restore set.
2395 // The eventual message back into the Package Manager to run the post-install
2396 // steps for 'token' will be issued from the restore handling code.
2397
2398 // We can use a synthetic PackageInfo here because:
2399 // 1. We know it's valid, since the Package Manager supplied the name
2400 // 2. Only the packageName field will be used by the restore code
2401 PackageInfo pkg = new PackageInfo();
2402 pkg.packageName = packageName;
2403
2404 mWakelock.acquire();
2405 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2406 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tatebbff7ed2010-10-29 12:57:04 -07002407 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002408 mBackupHandler.sendMessage(msg);
2409 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002410 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2411 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002412 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002413 try {
2414 mPackageManagerBinder.finishPackageInstall(token);
2415 } catch (RemoteException e) { /* can't happen */ }
2416 }
2417 }
2418
Christopher Tate8c850b72009-06-07 19:33:20 -07002419 // Hand off a restore session
Chris Tate6ec91732010-11-16 15:10:49 -08002420 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2421 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2422 + " transport=" + transport);
2423
2424 boolean needPermission = true;
2425 if (transport == null) {
2426 transport = mCurrentTransport;
2427
2428 if (packageName != null) {
2429 PackageInfo app = null;
2430 try {
2431 app = mPackageManager.getPackageInfo(packageName, 0);
2432 } catch (NameNotFoundException nnf) {
2433 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2434 throw new IllegalArgumentException("Package " + packageName + " not found");
2435 }
2436
2437 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2438 // So: using the current active transport, and the caller has asked
2439 // that its own package will be restored. In this narrow use case
2440 // we do not require the caller to hold the permission.
2441 needPermission = false;
2442 }
2443 }
2444 }
2445
2446 if (needPermission) {
2447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2448 "beginRestoreSession");
2449 } else {
2450 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2451 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002452
2453 synchronized(this) {
2454 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002455 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002456 return null;
2457 }
Chris Tate6ec91732010-11-16 15:10:49 -08002458 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002459 }
2460 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002461 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002462
Christopher Tate44a27902010-01-27 17:15:49 -08002463 // Note that a currently-active backup agent has notified us that it has
2464 // completed the given outstanding asynchronous backup/restore operation.
2465 public void opComplete(int token) {
2466 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002467 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002468 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2469 mCurrentOpLock.notifyAll();
2470 }
2471 }
2472
Christopher Tate9b3905c2009-06-08 15:24:01 -07002473 // ----- Restore session -----
2474
Christopher Tate80202c82010-01-25 19:37:47 -08002475 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002476 private static final String TAG = "RestoreSession";
2477
Chris Tate6ec91732010-11-16 15:10:49 -08002478 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002479 private IBackupTransport mRestoreTransport = null;
2480 RestoreSet[] mRestoreSets = null;
2481
Chris Tate6ec91732010-11-16 15:10:49 -08002482 ActiveRestoreSession(String packageName, String transport) {
2483 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07002484 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002485 }
2486
2487 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002488 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002489 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002490 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002491 if (observer == null) {
2492 throw new IllegalArgumentException("Observer must not be null");
2493 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002494
Christopher Tate1bb69062010-02-19 17:02:12 -08002495 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002496 try {
Christopher Tate43383042009-07-13 15:17:13 -07002497 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002498 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002499 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002500 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002501 // spin off the transport request to our service thread
2502 mWakelock.acquire();
2503 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2504 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2505 mBackupHandler.sendMessage(msg);
2506 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002507 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002508 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002509 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002510 } finally {
2511 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002512 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002513 }
2514
Christopher Tate84725812010-02-04 15:52:40 -08002515 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002516 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2517 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002518
Chris Tate6ec91732010-11-16 15:10:49 -08002519 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002520 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002521
Dan Egnor0084da52009-07-29 12:57:16 -07002522 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate6ec91732010-11-16 15:10:49 -08002523 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
2524 return -1;
2525 }
2526
2527 if (mPackageName != null) {
2528 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07002529 return -1;
2530 }
2531
Christopher Tate21ab6a52009-09-24 18:01:46 -07002532 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002533 for (int i = 0; i < mRestoreSets.length; i++) {
2534 if (token == mRestoreSets[i].token) {
2535 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002536 mWakelock.acquire();
2537 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tatebbff7ed2010-10-29 12:57:04 -07002538 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07002539 mBackupHandler.sendMessage(msg);
2540 Binder.restoreCallingIdentity(oldId);
2541 return 0;
2542 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002543 }
2544 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002545
Joe Onorato8a9b2202010-02-26 18:56:32 -08002546 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002547 return -1;
2548 }
2549
Christopher Tate84725812010-02-04 15:52:40 -08002550 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002551 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002552
Chris Tate6ec91732010-11-16 15:10:49 -08002553 if (mPackageName != null) {
2554 if (! mPackageName.equals(packageName)) {
2555 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
2556 + " on session for package " + mPackageName);
2557 return -1;
2558 }
2559 }
2560
Christopher Tate84725812010-02-04 15:52:40 -08002561 PackageInfo app = null;
2562 try {
2563 app = mPackageManager.getPackageInfo(packageName, 0);
2564 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002565 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002566 return -1;
2567 }
2568
2569 // If the caller is not privileged and is not coming from the target
2570 // app's uid, throw a permission exception back to the caller.
2571 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2572 Binder.getCallingPid(), Binder.getCallingUid());
2573 if ((perm == PackageManager.PERMISSION_DENIED) &&
2574 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002575 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002576 + " or calling uid=" + Binder.getCallingUid());
2577 throw new SecurityException("No permission to restore other packages");
2578 }
2579
Christopher Tate7d411a32010-02-26 11:27:08 -08002580 // If the package has no backup agent, we obviously cannot proceed
2581 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002582 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002583 return -1;
2584 }
2585
Christopher Tate84725812010-02-04 15:52:40 -08002586 // So far so good; we're allowed to try to restore this package. Now
2587 // check whether there is data for it in the current dataset, falling back
2588 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002589 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002590
2591 // If we didn't come up with a place to look -- no ancestral dataset and
2592 // the app has never been backed up from this device -- there's nothing
2593 // to do but return failure.
2594 if (token == 0) {
Chris Tate6ec91732010-11-16 15:10:49 -08002595 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08002596 return -1;
2597 }
2598
2599 // Ready to go: enqueue the restore request and claim success
2600 long oldId = Binder.clearCallingIdentity();
2601 mWakelock.acquire();
2602 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tatebbff7ed2010-10-29 12:57:04 -07002603 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08002604 mBackupHandler.sendMessage(msg);
2605 Binder.restoreCallingIdentity(oldId);
2606 return 0;
2607 }
2608
Dan Egnor0084da52009-07-29 12:57:16 -07002609 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002610 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002611
Dan Egnor0084da52009-07-29 12:57:16 -07002612 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002613 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002614 try {
2615 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2616 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002617 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002618 } finally {
2619 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002620 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002621 }
2622 }
2623
2624 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002625 if (BackupManagerService.this.mActiveRestoreSession == this) {
2626 BackupManagerService.this.mActiveRestoreSession = null;
2627 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002628 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002629 }
2630 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002631 }
2632 }
2633
Christopher Tate043dadc2009-06-02 16:11:00 -07002634
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002635 @Override
2636 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2637 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002638 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002639 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002640 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002641 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002642 pw.println("Last backup pass: " + mLastBackupPass
2643 + " (now = " + System.currentTimeMillis() + ')');
2644 pw.println(" next scheduled: " + mNextBackupPass);
2645
Christopher Tate91717492009-06-26 21:07:13 -07002646 pw.println("Available transports:");
2647 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002648 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2649 try {
2650 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2651 for (File f : dir.listFiles()) {
2652 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2653 }
2654 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002655 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002656 pw.println(" Error: " + e);
2657 }
Christopher Tate91717492009-06-26 21:07:13 -07002658 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002659
2660 pw.println("Pending init: " + mPendingInits.size());
2661 for (String s : mPendingInits) {
2662 pw.println(" " + s);
2663 }
2664
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002665 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002666 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002667 for (int i=0; i<N; i++) {
2668 int uid = mBackupParticipants.keyAt(i);
2669 pw.print(" uid: ");
2670 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002671 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2672 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002673 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002674 }
2675 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002676
Christopher Tateb49ceb32010-02-08 16:22:24 -08002677 pw.println("Ancestral packages: "
2678 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002679 if (mAncestralPackages != null) {
2680 for (String pkg : mAncestralPackages) {
2681 pw.println(" " + pkg);
2682 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002683 }
2684
Christopher Tate73e02522009-07-15 14:18:26 -07002685 pw.println("Ever backed up: " + mEverStoredApps.size());
2686 for (String pkg : mEverStoredApps) {
2687 pw.println(" " + pkg);
2688 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002689
2690 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002691 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002692 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002693 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002694 }
2695 }
Christopher Tate487529a2009-04-29 14:03:25 -07002696}