blob: 2651fd30964ff48a96bb306169a960dddfd73e4f [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.RestoreSet;
27import android.app.backup.IBackupManager;
28import android.app.backup.IRestoreObserver;
29import android.app.backup.IRestoreSession;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070031import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.content.Context;
33import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070036import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070037import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080038import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070039import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070041import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080042import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070045import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080050import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070052import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070053import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070057import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070059import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080062import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070063
Christopher Tated55e18a2009-09-21 10:12:59 -070064import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070065import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070067import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070068
Christopher Tatecde87f42009-06-12 12:55:53 -070069import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070070import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080072import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070073import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070074import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070075import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040077import java.util.ArrayList;
78import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070079import java.util.HashSet;
80import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070081import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070082import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080083import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070084
85class BackupManagerService extends IBackupManager.Stub {
86 private static final String TAG = "BackupManagerService";
Chris Tatea9c50432010-10-11 14:37:12 -070087 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070088
Christopher Tate49401dd2009-07-01 12:34:29 -070089 // How often we perform a backup pass. Privileged external callers can
90 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070091 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070092
Dan Egnorc1c49c02009-10-30 17:35:39 -070093 // Random variation in backup scheduling time to avoid server load spikes
94 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
95
Christopher Tate8031a3d2009-07-06 16:36:05 -070096 // The amount of time between the initial provisioning of the device and
97 // the first backup pass.
98 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
99
Christopher Tate45281862010-03-05 15:46:30 -0800100 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
101 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
102 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700103 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700104 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700105 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700106 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700107 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700108 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
109 private static final int MSG_TIMEOUT = 7;
Christopher 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 Tate249345b2010-10-29 12:57:04 -0700201 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800202
203 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-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 Tate249345b2010-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 Tate249345b2010-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 Tate249345b2010-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 Tate249345b2010-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 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800593 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800594 } catch (FileNotFoundException fnf) {
595 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800596 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800597 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800598 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800599 }
600
Christopher Tatee97e8072009-07-15 16:45:50 -0700601 // Keep a log of what apps we've ever backed up. Because we might have
602 // rebooted in the middle of an operation that was removing something from
603 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700604 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700605 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700606
Christopher Tatee97e8072009-07-15 16:45:50 -0700607 // If we were in the middle of removing something from the ever-backed-up
608 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700609 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700610 if (tempProcessedFile.exists()) {
611 tempProcessedFile.delete();
612 }
613
Dan Egnor852f8e42009-09-30 11:20:45 -0700614 // If there are previous contents, parse them out then start a new
615 // file to continue the recordkeeping.
616 if (mEverStored.exists()) {
617 RandomAccessFile temp = null;
618 RandomAccessFile in = null;
619
620 try {
621 temp = new RandomAccessFile(tempProcessedFile, "rws");
622 in = new RandomAccessFile(mEverStored, "r");
623
624 while (true) {
625 PackageInfo info;
626 String pkg = in.readUTF();
627 try {
628 info = mPackageManager.getPackageInfo(pkg, 0);
629 mEverStoredApps.add(pkg);
630 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800631 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700632 } catch (NameNotFoundException e) {
633 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800634 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700635 }
636 }
637 } catch (EOFException e) {
638 // Once we've rewritten the backup history log, atomically replace the
639 // old one with the new one then reopen the file for continuing use.
640 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800641 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700642 }
643 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800644 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700645 } finally {
646 try { if (temp != null) temp.close(); } catch (IOException e) {}
647 try { if (in != null) in.close(); } catch (IOException e) {}
648 }
649 }
650
Christopher Tate73e02522009-07-15 14:18:26 -0700651 // Register for broadcasts about package install, etc., so we can
652 // update the provider list.
653 IntentFilter filter = new IntentFilter();
654 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
655 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
656 filter.addDataScheme("package");
657 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800658 // Register for events related to sdcard installation.
659 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800660 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
661 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800662 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700663 }
664
Christopher Tatecde87f42009-06-12 12:55:53 -0700665 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700666 for (File f : mJournalDir.listFiles()) {
667 if (mJournal == null || f.compareTo(mJournal) != 0) {
668 // This isn't the current journal, so it must be a leftover. Read
669 // out the package names mentioned there and schedule them for
670 // backup.
671 RandomAccessFile in = null;
672 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400673 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700674 in = new RandomAccessFile(f, "r");
675 while (true) {
676 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400677 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700678 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700679 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700680 } catch (EOFException e) {
681 // no more data; we're done
682 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800683 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700684 } finally {
685 // close/delete the file
686 try { if (in != null) in.close(); } catch (IOException e) {}
687 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700688 }
689 }
690 }
691 }
692
Christopher Tate4cc86e12009-09-21 19:36:51 -0700693 // Maintain persistent state around whether need to do an initialize operation.
694 // Must be called with the queue lock held.
695 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800696 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700697 + " on transport " + transportName);
698 try {
699 IBackupTransport transport = getTransport(transportName);
700 String transportDirName = transport.transportDirName();
701 File stateDir = new File(mBaseStateDir, transportDirName);
702 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
703
704 if (isPending) {
705 // We need an init before we can proceed with sending backup data.
706 // Record that with an entry in our set of pending inits, as well as
707 // journaling it via creation of a sentinel file.
708 mPendingInits.add(transportName);
709 try {
710 (new FileOutputStream(initPendingFile)).close();
711 } catch (IOException ioe) {
712 // Something is badly wrong with our permissions; just try to move on
713 }
714 } else {
715 // No more initialization needed; wipe the journal and reset our state.
716 initPendingFile.delete();
717 mPendingInits.remove(transportName);
718 }
719 } catch (RemoteException e) {
720 // can't happen; the transport is local
721 }
722 }
723
Christopher Tated55e18a2009-09-21 10:12:59 -0700724 // Reset all of our bookkeeping, in response to having been told that
725 // the backend data has been wiped [due to idle expiry, for example],
726 // so we must re-upload all saved settings.
727 void resetBackupState(File stateFileDir) {
728 synchronized (mQueueLock) {
729 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700730 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700731 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700732
Christopher Tate84725812010-02-04 15:52:40 -0800733 mCurrentToken = 0;
734 writeRestoreTokens();
735
Christopher Tated55e18a2009-09-21 10:12:59 -0700736 // Remove all the state files
737 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700738 // ... but don't touch the needs-init sentinel
739 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
740 sf.delete();
741 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700742 }
743
744 // Enqueue a new backup of every participant
745 int N = mBackupParticipants.size();
746 for (int i=0; i<N; i++) {
747 int uid = mBackupParticipants.keyAt(i);
748 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
749 for (ApplicationInfo app: participants) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700750 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700751 }
752 }
753 }
754 }
755
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800756 // Add a transport to our set of available backends. If 'transport' is null, this
757 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700758 private void registerTransport(String name, IBackupTransport transport) {
759 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800760 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800761 if (transport != null) {
762 mTransports.put(name, transport);
763 } else {
764 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800765 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800766 mCurrentTransport = null;
767 }
768 // Nothing further to do in the unregistration case
769 return;
770 }
Christopher Tate91717492009-06-26 21:07:13 -0700771 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700772
773 // If the init sentinel file exists, we need to be sure to perform the init
774 // as soon as practical. We also create the state directory at registration
775 // time to ensure it's present from the outset.
776 try {
777 String transportName = transport.transportDirName();
778 File stateDir = new File(mBaseStateDir, transportName);
779 stateDir.mkdirs();
780
781 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
782 if (initSentinel.exists()) {
783 synchronized (mQueueLock) {
784 mPendingInits.add(transportName);
785
786 // TODO: pick a better starting time than now + 1 minute
787 long delay = 1000 * 60; // one minute, in milliseconds
788 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
789 System.currentTimeMillis() + delay, mRunInitIntent);
790 }
791 }
792 } catch (RemoteException e) {
793 // can't happen, the transport is local
794 }
Christopher Tate91717492009-06-26 21:07:13 -0700795 }
796
Christopher Tate3799bc22009-05-06 16:13:56 -0700797 // ----- Track installation/removal of packages -----
798 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
799 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800800 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700801
Christopher Tate3799bc22009-05-06 16:13:56 -0700802 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800803 boolean replacing = false;
804 boolean added = false;
805 Bundle extras = intent.getExtras();
806 String pkgList[] = null;
807 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
808 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
809 Uri uri = intent.getData();
810 if (uri == null) {
811 return;
812 }
813 String pkgName = uri.getSchemeSpecificPart();
814 if (pkgName != null) {
815 pkgList = new String[] { pkgName };
816 }
817 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
818 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800819 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800820 added = true;
821 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800822 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800823 added = false;
824 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
825 }
826 if (pkgList == null || pkgList.length == 0) {
827 return;
828 }
829 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700830 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800831 for (String pkgName : pkgList) {
832 if (replacing) {
833 // The package was just upgraded
834 updatePackageParticipantsLocked(pkgName);
835 } else {
836 // The package was just added
837 addPackageParticipantsLocked(pkgName);
838 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700839 }
840 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800841 } else {
842 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700843 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
844 } else {
845 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800846 for (String pkgName : pkgList) {
847 removePackageParticipantsLocked(pkgName);
848 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700849 }
850 }
851 }
852 }
853 };
854
Dan Egnor87a02bc2009-06-17 02:30:10 -0700855 // ----- Track connection to GoogleBackupTransport service -----
856 ServiceConnection mGoogleConnection = new ServiceConnection() {
857 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800858 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700859 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700860 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700861 }
862
863 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800864 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700865 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700866 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700867 }
868 };
869
Christopher Tate181fafa2009-05-14 11:12:14 -0700870 // Add the backup agents in the given package to our set of known backup participants.
871 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700872 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700873 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800874 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700875 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700876 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700877 }
878
Christopher Tate181fafa2009-05-14 11:12:14 -0700879 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700880 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700881 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800882 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700883 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800884 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700885 + " uid=" + p.applicationInfo.uid
886 + " killAfterRestore="
887 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700888 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700889 }
890 }
891
Dan Egnorefe52642009-06-24 00:16:33 -0700892 for (PackageInfo pkg : targetPkgs) {
893 if (packageName == null || pkg.packageName.equals(packageName)) {
894 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700895 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700896 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700897 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700898 mBackupParticipants.put(uid, set);
899 }
Dan Egnorefe52642009-06-24 00:16:33 -0700900 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700901
902 // If we've never seen this app before, schedule a backup for it
903 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700905 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700906 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700907 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700908 }
Christopher Tate487529a2009-04-29 14:03:25 -0700909 }
910 }
911
Christopher Tate6785dd82009-06-18 15:58:25 -0700912 // Remove the given package's entry from our known active set. If
913 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700914 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800915 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700916 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700917 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700918 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700919 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700920 int flags = PackageManager.GET_SIGNATURES;
921 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700922 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700923 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700924 }
925 } else {
926 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700927 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700928 }
929 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700930 }
931
Joe Onorato8ad02812009-05-13 01:41:44 -0400932 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700933 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700934 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800935 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700936 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700937 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800938 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700939 }
940 }
Dan Egnorefe52642009-06-24 00:16:33 -0700941 for (PackageInfo pkg : agents) {
942 if (packageName == null || pkg.packageName.equals(packageName)) {
943 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700944 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700945 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700946 // Find the existing entry with the same package name, and remove it.
947 // We can't just remove(app) because the instances are different.
948 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700949 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700950 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700951 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700952 break;
953 }
954 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700955 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700956 mBackupParticipants.delete(uid);
957 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700958 }
959 }
960 }
961 }
962
Christopher Tate181fafa2009-05-14 11:12:14 -0700963 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700964 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700965 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700966 int flags = PackageManager.GET_SIGNATURES;
967 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
968 int N = packages.size();
969 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700970 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700971 try {
972 ApplicationInfo app = pkg.applicationInfo;
973 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800974 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700975 packages.remove(a);
976 }
977 else {
978 // we will need the shared library path, so look that up and store it here
979 app = mPackageManager.getApplicationInfo(pkg.packageName,
980 PackageManager.GET_SHARED_LIBRARY_FILES);
981 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
982 }
983 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700984 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700985 }
986 }
Dan Egnorefe52642009-06-24 00:16:33 -0700987 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700988 }
Christopher Tateaa088442009-06-16 18:25:46 -0700989
Christopher Tate3799bc22009-05-06 16:13:56 -0700990 // Reset the given package's known backup participants. Unlike add/remove, the update
991 // action cannot be passed a null package name.
992 void updatePackageParticipantsLocked(String packageName) {
993 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800994 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700995 return;
996 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700998
999 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001000 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001001 removePackageParticipantsLockedInner(packageName, allApps);
1002 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001003 }
1004
Christopher Tate84725812010-02-04 15:52:40 -08001005 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001006 // backed up at least once
1007 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001008 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1009
1010 synchronized (mEverStoredApps) {
1011 if (!mEverStoredApps.add(packageName)) return;
1012
1013 RandomAccessFile out = null;
1014 try {
1015 out = new RandomAccessFile(mEverStored, "rws");
1016 out.seek(out.length());
1017 out.writeUTF(packageName);
1018 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001020 } finally {
1021 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001022 }
1023 }
1024 }
1025
Christopher Tatee97e8072009-07-15 16:45:50 -07001026 // Remove our awareness of having ever backed up the given package
1027 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001029
Dan Egnor852f8e42009-09-30 11:20:45 -07001030 synchronized (mEverStoredApps) {
1031 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1032 // we'll recognize on initialization time that the package no longer
1033 // exists and fix it up then.
1034 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1035 RandomAccessFile known = null;
1036 try {
1037 known = new RandomAccessFile(tempKnownFile, "rws");
1038 mEverStoredApps.remove(packageName);
1039 for (String s : mEverStoredApps) {
1040 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001041 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001042 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001043 known.close();
1044 known = null;
1045 if (!tempKnownFile.renameTo(mEverStored)) {
1046 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1047 }
1048 } catch (IOException e) {
1049 // Bad: we couldn't create the new copy. For safety's sake we
1050 // abandon the whole process and remove all what's-backed-up
1051 // state entirely, meaning we'll force a backup pass for every
1052 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001053 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001054 mEverStoredApps.clear();
1055 tempKnownFile.delete();
1056 mEverStored.delete();
1057 } finally {
1058 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001059 }
1060 }
1061 }
1062
Christopher Tateb49ceb32010-02-08 16:22:24 -08001063 // Persistently record the current and ancestral backup tokens as well
1064 // as the set of packages with data [supposedly] available in the
1065 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001066 void writeRestoreTokens() {
1067 try {
1068 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001069
1070 // First, the version number of this record, for futureproofing
1071 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1072
1073 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001074 af.writeLong(mAncestralToken);
1075 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001076
1077 // Now write the set of ancestral packages
1078 if (mAncestralPackages == null) {
1079 af.writeInt(-1);
1080 } else {
1081 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001082 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001083 for (String pkgName : mAncestralPackages) {
1084 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001085 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001086 }
1087 }
Christopher Tate84725812010-02-04 15:52:40 -08001088 af.close();
1089 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001090 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001091 }
1092 }
1093
Dan Egnor87a02bc2009-06-17 02:30:10 -07001094 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001095 private IBackupTransport getTransport(String transportName) {
1096 synchronized (mTransports) {
1097 IBackupTransport transport = mTransports.get(transportName);
1098 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001099 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001100 }
1101 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001102 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001103 }
1104
Christopher Tatedf01dea2009-06-09 20:45:02 -07001105 // fire off a backup agent, blocking until it attaches or times out
1106 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1107 IBackupAgent agent = null;
1108 synchronized(mAgentConnectLock) {
1109 mConnecting = true;
1110 mConnectedAgent = null;
1111 try {
1112 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001113 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001114
1115 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001116 // only wait 10 seconds for the clear data to happen
1117 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1118 while (mConnecting && mConnectedAgent == null
1119 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001120 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001121 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001122 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001123 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001124 return null;
1125 }
1126 }
1127
1128 // if we timed out with no connect, abort and move on
1129 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001130 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001131 return null;
1132 }
1133 agent = mConnectedAgent;
1134 }
1135 } catch (RemoteException e) {
1136 // can't happen
1137 }
1138 }
1139 return agent;
1140 }
1141
Christopher Tatec7b31e32009-06-10 15:49:30 -07001142 // clear an application's data, blocking until the operation completes or times out
1143 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001144 // Don't wipe packages marked allowClearUserData=false
1145 try {
1146 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1147 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001148 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001149 + packageName);
1150 return;
1151 }
1152 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001154 return;
1155 }
1156
Christopher Tatec7b31e32009-06-10 15:49:30 -07001157 ClearDataObserver observer = new ClearDataObserver();
1158
1159 synchronized(mClearDataLock) {
1160 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001161 try {
1162 mActivityManager.clearApplicationUserData(packageName, observer);
1163 } catch (RemoteException e) {
1164 // can't happen because the activity manager is in this process
1165 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001166
1167 // only wait 10 seconds for the clear data to happen
1168 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1169 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1170 try {
1171 mClearDataLock.wait(5000);
1172 } catch (InterruptedException e) {
1173 // won't happen, but still.
1174 mClearingData = false;
1175 }
1176 }
1177 }
1178 }
1179
1180 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001181 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001182 synchronized(mClearDataLock) {
1183 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001184 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001185 }
1186 }
1187 }
1188
Christopher Tate1bb69062010-02-19 17:02:12 -08001189 // Get the restore-set token for the best-available restore set for this package:
1190 // the active set if possible, else the ancestral one. Returns zero if none available.
1191 long getAvailableRestoreToken(String packageName) {
1192 long token = mAncestralToken;
1193 synchronized (mQueueLock) {
1194 if (mEverStoredApps.contains(packageName)) {
1195 token = mCurrentToken;
1196 }
1197 }
1198 return token;
1199 }
1200
Christopher Tate44a27902010-01-27 17:15:49 -08001201 // -----
1202 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1203 boolean waitUntilOperationComplete(int token) {
1204 int finalState = OP_PENDING;
1205 synchronized (mCurrentOpLock) {
1206 try {
1207 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1208 try {
1209 mCurrentOpLock.wait();
1210 } catch (InterruptedException e) {}
1211 }
1212 } catch (IndexOutOfBoundsException e) {
1213 // the operation has been mysteriously cleared from our
1214 // bookkeeping -- consider this a success and ignore it.
1215 }
1216 }
1217 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001218 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001219 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001220 return finalState == OP_ACKNOWLEDGED;
1221 }
1222
1223 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001225 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001226 mCurrentOperations.put(token, OP_PENDING);
1227 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1228 mBackupHandler.sendMessageDelayed(msg, interval);
1229 }
1230
Christopher Tate043dadc2009-06-02 16:11:00 -07001231 // ----- Back up a set of applications via a worker thread -----
1232
Christopher Tate44a27902010-01-27 17:15:49 -08001233 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001234 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001235 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001236 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001237 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001238 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001239
Christopher Tate44a27902010-01-27 17:15:49 -08001240 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001241 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001242 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001243 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001244 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001245
1246 try {
1247 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1248 } catch (RemoteException e) {
1249 // can't happen; the transport is local
1250 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001251 }
1252
Christopher Tate043dadc2009-06-02 16:11:00 -07001253 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001254 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001256 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001257
Christopher Tate79588342009-06-30 16:11:49 -07001258 // Backups run at background priority
1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1260
Christopher Tate043dadc2009-06-02 16:11:00 -07001261 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001262 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001263
Dan Egnor852f8e42009-09-30 11:20:45 -07001264 // If we haven't stored package manager metadata yet, we must init the transport.
1265 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1266 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001267 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001268 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001269 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001270 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001271 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001272 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001273 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001274 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001275 }
Dan Egnor01445162009-09-21 17:04:05 -07001276 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001277
1278 // The package manager doesn't have a proper <application> etc, but since
1279 // it's running here in the system process we can just set up its agent
1280 // directly and use a synthetic BackupRequest. We always run this pass
1281 // because it's cheap and this way we guarantee that we don't get out of
1282 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001283 if (status == BackupConstants.TRANSPORT_OK) {
1284 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1285 mPackageManager, allAgentPackages());
1286 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1287 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1288 status = processOneBackup(pmRequest,
1289 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1290 }
Christopher Tate90967f42009-09-20 15:28:33 -07001291
Dan Egnor01445162009-09-21 17:04:05 -07001292 if (status == BackupConstants.TRANSPORT_OK) {
1293 // Now run all the backups in our queue
1294 status = doQueuedBackups(mTransport);
1295 }
1296
1297 if (status == BackupConstants.TRANSPORT_OK) {
1298 // Tell the transport to finish everything it has buffered
1299 status = mTransport.finishBackup();
1300 if (status == BackupConstants.TRANSPORT_OK) {
1301 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001302 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001303 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001304 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001305 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001306 }
1307 }
1308
Dan Egnor01445162009-09-21 17:04:05 -07001309 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001310 // The backend reports that our dataset has been wiped. We need to
1311 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001312 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001313 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001314 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001315 }
1316 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001317 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001318 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001319 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001320 // If everything actually went through and this is the first time we've
1321 // done a backup, we can now record what the current backup dataset token
1322 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001323 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001324 try {
1325 mCurrentToken = mTransport.getCurrentRestoreSet();
1326 } catch (RemoteException e) { /* cannot happen */ }
1327 writeRestoreTokens();
1328 }
1329
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001330 // If things went wrong, we need to re-stage the apps we had expected
1331 // to be backing up in this pass. This journals the package names in
1332 // the current active pending-backup file, not in the we are holding
1333 // here in mJournal.
1334 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001335 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001336 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001337 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001338 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001339
1340 // We also want to reset the backup schedule based on whatever
1341 // the transport suggests by way of retry/backoff time.
1342 try {
1343 startBackupAlarmsLocked(mTransport.requestBackupTime());
1344 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001345 }
1346
1347 // Either backup was successful, in which case we of course do not need
1348 // this pass's journal any more; or it failed, in which case we just
1349 // re-enqueued all of these packages in the current active journal.
1350 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001351 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001352 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001353 }
1354
Christopher Tatec2af5d32010-02-02 15:18:58 -08001355 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001356 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001357 backupNow();
1358 }
1359
Dan Egnorbb9001c2009-07-27 12:20:13 -07001360 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001361 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001362 }
1363
Dan Egnor01445162009-09-21 17:04:05 -07001364 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001365 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001366 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001367
1368 IBackupAgent agent = null;
1369 int mode = (request.fullBackup)
1370 ? IApplicationThread.BACKUP_MODE_FULL
1371 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1372 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001373 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001374 agent = bindToAgentSynchronous(request.appInfo, mode);
1375 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001376 int result = processOneBackup(request, agent, transport);
1377 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001379 } catch (SecurityException ex) {
1380 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001382 } finally {
1383 try { // unbind even on timeout, just in case
1384 mActivityManager.unbindBackupAgent(request.appInfo);
1385 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001386 }
1387 }
Dan Egnor01445162009-09-21 17:04:05 -07001388
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001389 mWakelock.setWorkSource(null);
1390
Dan Egnor01445162009-09-21 17:04:05 -07001391 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001392 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001393
Dan Egnor01445162009-09-21 17:04:05 -07001394 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1395 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001396 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001398
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 File savedStateName = new File(mStateDir, packageName);
1400 File backupDataName = new File(mDataDir, packageName + ".data");
1401 File newStateName = new File(mStateDir, packageName + ".new");
1402
1403 ParcelFileDescriptor savedState = null;
1404 ParcelFileDescriptor backupData = null;
1405 ParcelFileDescriptor newState = null;
1406
1407 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001408 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001409 try {
1410 // Look up the package info & signatures. This is first so that if it
1411 // throws an exception, there's no file setup yet that would need to
1412 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001413 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1414 // The metadata 'package' is synthetic
1415 packInfo = new PackageInfo();
1416 packInfo.packageName = packageName;
1417 } else {
1418 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001419 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001420 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001421
Christopher Tatec7b31e32009-06-10 15:49:30 -07001422 // In a full backup, we pass a null ParcelFileDescriptor as
1423 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001424 if (!request.fullBackup) {
1425 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001426 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001427 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1428 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001429
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430 backupData = ParcelFileDescriptor.open(backupDataName,
1431 ParcelFileDescriptor.MODE_READ_WRITE |
1432 ParcelFileDescriptor.MODE_CREATE |
1433 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001434
Dan Egnorbb9001c2009-07-27 12:20:13 -07001435 newState = ParcelFileDescriptor.open(newStateName,
1436 ParcelFileDescriptor.MODE_READ_WRITE |
1437 ParcelFileDescriptor.MODE_CREATE |
1438 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001439
Christopher Tate44a27902010-01-27 17:15:49 -08001440 // Initiate the target's backup pass
1441 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1442 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1443 boolean success = waitUntilOperationComplete(token);
1444
1445 if (!success) {
1446 // timeout -- bail out into the failed-transaction logic
1447 throw new RuntimeException("Backup timeout");
1448 }
1449
Dan Egnorbb9001c2009-07-27 12:20:13 -07001450 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001451 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001452 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001453 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001455 backupDataName.delete();
1456 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001457 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001458 } finally {
1459 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1460 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1461 try { if (newState != null) newState.close(); } catch (IOException e) {}
1462 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001463 synchronized (mCurrentOpLock) {
1464 mCurrentOperations.clear();
1465 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 }
1467
1468 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001469 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001470 try {
1471 int size = (int) backupDataName.length();
1472 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001473 if (result == BackupConstants.TRANSPORT_OK) {
1474 backupData = ParcelFileDescriptor.open(backupDataName,
1475 ParcelFileDescriptor.MODE_READ_ONLY);
1476 result = transport.performBackup(packInfo, backupData);
1477 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001478
Dan Egnor83861e72009-09-17 16:17:55 -07001479 // TODO - We call finishBackup() for each application backed up, because
1480 // we need to know now whether it succeeded or failed. Instead, we should
1481 // hold off on finishBackup() until the end, which implies holding off on
1482 // renaming *all* the output state files (see below) until that happens.
1483
Dan Egnor01445162009-09-21 17:04:05 -07001484 if (result == BackupConstants.TRANSPORT_OK) {
1485 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001486 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001487 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001489 }
1490
1491 // After successful transport, delete the now-stale data
1492 // and juggle the files so that next time we supply the agent
1493 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001494 if (result == BackupConstants.TRANSPORT_OK) {
1495 backupDataName.delete();
1496 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001497 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001498 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001499 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001500 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001501 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001502 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001503 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001504 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001505 } finally {
1506 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001507 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001508
Dan Egnor01445162009-09-21 17:04:05 -07001509 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001510 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001511 }
1512
Christopher Tatedf01dea2009-06-09 20:45:02 -07001513
1514 // ----- Restore handling -----
1515
Christopher Tate78dd4a72009-11-04 11:49:08 -08001516 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1517 // If the target resides on the system partition, we allow it to restore
1518 // data from the like-named package in a restore set even if the signatures
1519 // do not match. (Unlike general applications, those flashed to the system
1520 // partition will be signed with the device's platform certificate, so on
1521 // different phones the same system app will have different signatures.)
1522 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001524 return true;
1525 }
1526
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001527 // Allow unsigned apps, but not signed on one device and unsigned on the other
1528 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001529 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001530 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001531 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001532 if ((storedSigs == null || storedSigs.length == 0)
1533 && (deviceSigs == null || deviceSigs.length == 0)) {
1534 return true;
1535 }
1536 if (storedSigs == null || deviceSigs == null) {
1537 return false;
1538 }
1539
Christopher Tateabce4e82009-06-18 18:35:32 -07001540 // !!! TODO: this demands that every stored signature match one
1541 // that is present on device, and does not demand the converse.
1542 // Is this this right policy?
1543 int nStored = storedSigs.length;
1544 int nDevice = deviceSigs.length;
1545
1546 for (int i=0; i < nStored; i++) {
1547 boolean match = false;
1548 for (int j=0; j < nDevice; j++) {
1549 if (storedSigs[i].equals(deviceSigs[j])) {
1550 match = true;
1551 break;
1552 }
1553 }
1554 if (!match) {
1555 return false;
1556 }
1557 }
1558 return true;
1559 }
1560
Christopher Tate44a27902010-01-27 17:15:49 -08001561 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001562 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001563 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001564 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001565 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001566 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001567 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001568 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001569
Christopher Tate5cbbf562009-06-22 16:44:51 -07001570 class RestoreRequest {
1571 public PackageInfo app;
1572 public int storedAppVersion;
1573
1574 RestoreRequest(PackageInfo _app, int _version) {
1575 app = _app;
1576 storedAppVersion = _version;
1577 }
1578 }
1579
Christopher Tate44a27902010-01-27 17:15:49 -08001580 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001581 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1582 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001583 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001584 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001585 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001586 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001587 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001588 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001589
1590 try {
1591 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1592 } catch (RemoteException e) {
1593 // can't happen; the transport is local
1594 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001595 }
1596
Christopher Tatedf01dea2009-06-09 20:45:02 -07001597 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001598 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001599 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001600 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001601 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001602
Christopher Tateb49ceb32010-02-08 16:22:24 -08001603 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001604 int error = -1; // assume error
1605
Dan Egnorefe52642009-06-24 00:16:33 -07001606 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001607 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001608 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001610
Dan Egnorefe52642009-06-24 00:16:33 -07001611 // Get the list of all packages which have backup enabled.
1612 // (Include the Package Manager metadata pseudo-package first.)
1613 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1614 PackageInfo omPackage = new PackageInfo();
1615 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1616 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001617
Dan Egnorefe52642009-06-24 00:16:33 -07001618 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001619 if (mTargetPackage == null) {
1620 restorePackages.addAll(agentPackages);
1621 } else {
1622 // Just one package to attempt restore of
1623 restorePackages.add(mTargetPackage);
1624 }
Dan Egnorefe52642009-06-24 00:16:33 -07001625
Christopher Tate7d562ec2009-06-25 18:03:43 -07001626 // let the observer know that we're running
1627 if (mObserver != null) {
1628 try {
1629 // !!! TODO: get an actual count from the transport after
1630 // its startRestore() runs?
1631 mObserver.restoreStarting(restorePackages.size());
1632 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001633 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001634 mObserver = null;
1635 }
1636 }
1637
Dan Egnor01445162009-09-21 17:04:05 -07001638 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1639 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001641 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001642 return;
1643 }
1644
1645 String packageName = mTransport.nextRestorePackage();
1646 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001648 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001649 return;
1650 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001651 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001652 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001654 return;
1655 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001656 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001657 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001658 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001659 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001660 return;
1661 }
1662
1663 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001664 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001665 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07001666 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
1667 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07001668
Christopher Tate8c032472009-07-02 14:28:47 -07001669 // Verify that the backup set includes metadata. If not, we can't do
1670 // signature/version verification etc, so we simply do not proceed with
1671 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001672 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001673 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001674 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001675 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001676 return;
1677 }
1678
Christopher Tate7d562ec2009-06-25 18:03:43 -07001679 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001680 for (;;) {
1681 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001682
Dan Egnorefe52642009-06-24 00:16:33 -07001683 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001685 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001686 return;
1687 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001689 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001690 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001691
Christopher Tate7d562ec2009-06-25 18:03:43 -07001692 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001693 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001694 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001695 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001696 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001697 mObserver = null;
1698 }
1699 }
1700
Dan Egnorefe52642009-06-24 00:16:33 -07001701 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1702 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001704 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001705 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001706 continue;
1707 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001708
Dan Egnorbb9001c2009-07-27 12:20:13 -07001709 PackageInfo packageInfo;
1710 try {
1711 int flags = PackageManager.GET_SIGNATURES;
1712 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1713 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001715 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001716 "Package missing on device");
1717 continue;
1718 }
1719
Dan Egnorefe52642009-06-24 00:16:33 -07001720 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001721 // Data is from a "newer" version of the app than we have currently
1722 // installed. If the app has not declared that it is prepared to
1723 // handle this case, we do not attempt the restore.
1724 if ((packageInfo.applicationInfo.flags
1725 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1726 String message = "Version " + metaInfo.versionCode
1727 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001728 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001729 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1730 packageName, message);
1731 continue;
1732 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001733 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001734 + " > installed " + packageInfo.versionCode
1735 + " but restoreAnyVersion");
1736 }
Dan Egnorefe52642009-06-24 00:16:33 -07001737 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001738
Christopher Tate78dd4a72009-11-04 11:49:08 -08001739 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001740 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001742 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001743 continue;
1744 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001745
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001747 + " restore version [" + metaInfo.versionCode
1748 + "] is compatible with installed version ["
1749 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001750
Christopher Tate3de55bc2010-03-12 17:28:08 -08001751 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001752 IBackupAgent agent = bindToAgentSynchronous(
1753 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001754 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001755 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001756 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001757 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001758 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001759 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001760 }
1761
Christopher Tate5e1ab332009-09-01 20:32:49 -07001762 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001763 try {
Chris Tate249345b2010-10-29 12:57:04 -07001764 processOneRestore(packageInfo, metaInfo.versionCode, agent,
1765 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001766 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001767 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001768 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001769 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001770
1771 // The agent was probably running with a stub Application object,
1772 // which isn't a valid run mode for the main app logic. Shut
1773 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001774 // usual full initialization. Note that this is only done for
1775 // full-system restores: when a single app has requested a restore,
1776 // it is explicitly not killed following that operation.
1777 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001778 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001779 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001780 + packageInfo.applicationInfo.processName);
1781 mActivityManager.killApplicationProcess(
1782 packageInfo.applicationInfo.processName,
1783 packageInfo.applicationInfo.uid);
1784 }
Dan Egnorefe52642009-06-24 00:16:33 -07001785 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001786 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001787
1788 // if we get this far, report success to the observer
1789 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001790 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001791 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001792 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001794 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001795 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001796
Dan Egnorefe52642009-06-24 00:16:33 -07001797 try {
1798 mTransport.finishRestore();
1799 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001800 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001801 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001802
1803 if (mObserver != null) {
1804 try {
1805 mObserver.restoreFinished(error);
1806 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001807 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001808 }
1809 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001810
Christopher Tate84725812010-02-04 15:52:40 -08001811 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001812 // ancestral dataset, as well as the set of apps that are possibly
1813 // restoreable from the dataset
1814 if (mTargetPackage == null && pmAgent != null) {
1815 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001816 mAncestralToken = mToken;
1817 writeRestoreTokens();
1818 }
1819
Christopher Tate1bb69062010-02-19 17:02:12 -08001820 // We must under all circumstances tell the Package Manager to
1821 // proceed with install notifications if it's waiting for us.
1822 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001823 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001824 try {
1825 mPackageManagerBinder.finishPackageInstall(mPmToken);
1826 } catch (RemoteException e) { /* can't happen */ }
1827 }
1828
Christopher Tateb6787f22009-07-02 17:40:45 -07001829 // done; we can finally release the wakelock
1830 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001831 }
1832 }
1833
Dan Egnorefe52642009-06-24 00:16:33 -07001834 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07001835 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
1836 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001837 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001838 final String packageName = app.packageName;
1839
Joe Onorato8a9b2202010-02-26 18:56:32 -08001840 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001841
Christopher Tatec7b31e32009-06-10 15:49:30 -07001842 // !!! TODO: get the dirs from the transport
1843 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001844 File newStateName = new File(mStateDir, packageName + ".new");
1845 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001846
Dan Egnorbb9001c2009-07-27 12:20:13 -07001847 ParcelFileDescriptor backupData = null;
1848 ParcelFileDescriptor newState = null;
1849
Christopher Tate44a27902010-01-27 17:15:49 -08001850 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001851 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001852 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 backupData = ParcelFileDescriptor.open(backupDataName,
1854 ParcelFileDescriptor.MODE_READ_WRITE |
1855 ParcelFileDescriptor.MODE_CREATE |
1856 ParcelFileDescriptor.MODE_TRUNCATE);
1857
Dan Egnor01445162009-09-21 17:04:05 -07001858 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001859 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001860 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001861 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001862 }
1863
1864 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001865 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001866 backupData = ParcelFileDescriptor.open(backupDataName,
1867 ParcelFileDescriptor.MODE_READ_ONLY);
1868
Dan Egnorbb9001c2009-07-27 12:20:13 -07001869 newState = ParcelFileDescriptor.open(newStateName,
1870 ParcelFileDescriptor.MODE_READ_WRITE |
1871 ParcelFileDescriptor.MODE_CREATE |
1872 ParcelFileDescriptor.MODE_TRUNCATE);
1873
Christopher Tate44a27902010-01-27 17:15:49 -08001874 // Kick off the restore, checking for hung agents
1875 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1876 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1877 boolean success = waitUntilOperationComplete(token);
1878
1879 if (!success) {
1880 throw new RuntimeException("restore timeout");
1881 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001882
1883 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001884 //
1885 // !!! TODO: the restored data should be migrated on the server
1886 // side into the current dataset. In that case the new state file
1887 // we just created would reflect the data already extant in the
1888 // backend, so there'd be nothing more to do. Until that happens,
1889 // however, we need to make sure that we record the data to the
1890 // current backend dataset. (Yes, this means shipping the data over
1891 // the wire in both directions. That's bad, but consistency comes
1892 // first, then efficiency.) Once we introduce server-side data
1893 // migration to the newly-restored device's dataset, we will change
1894 // the following from a discard of the newly-written state to the
1895 // "correct" operation of renaming into the canonical state blob.
1896 newStateName.delete(); // TODO: remove; see above comment
1897 //newStateName.renameTo(savedStateName); // TODO: replace with this
1898
Dan Egnorbb9001c2009-07-27 12:20:13 -07001899 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001900 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001901 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001902 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001903 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001904
Christopher Tate96733042009-07-20 14:49:13 -07001905 // If the agent fails restore, it might have put the app's data
1906 // into an incoherent state. For consistency we wipe its data
1907 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001908 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001909 } finally {
1910 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001911 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1912 try { if (newState != null) newState.close(); } catch (IOException e) {}
1913 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001914 mCurrentOperations.delete(token);
Chris Tate249345b2010-10-29 12:57:04 -07001915
1916 // If we know a priori that we'll need to perform a full post-restore backup
1917 // pass, clear the new state file data. This means we're discarding work that
1918 // was just done by the app's agent, but this way the agent doesn't need to
1919 // take any special action based on global device state.
1920 if (needFullBackup) {
1921 newStateName.delete();
1922 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001923 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001924 }
1925 }
1926
Christopher Tate44a27902010-01-27 17:15:49 -08001927 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001928 IBackupTransport mTransport;
1929 PackageInfo mPackage;
1930
Christopher Tate44a27902010-01-27 17:15:49 -08001931 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001932 mTransport = transport;
1933 mPackage = packageInfo;
1934 }
1935
Christopher Tateee0e78a2009-07-02 11:17:03 -07001936 public void run() {
1937 try {
1938 // Clear the on-device backup state to ensure a full backup next time
1939 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1940 File stateFile = new File(stateDir, mPackage.packageName);
1941 stateFile.delete();
1942
1943 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001944 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001945 mTransport.clearBackupData(mPackage);
1946 } catch (RemoteException e) {
1947 // can't happen; the transport is local
1948 } finally {
1949 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001950 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001951 mTransport.finishBackup();
1952 } catch (RemoteException e) {
1953 // can't happen; the transport is local
1954 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001955
1956 // Last but not least, release the cpu
1957 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001958 }
1959 }
1960 }
1961
Christopher Tate44a27902010-01-27 17:15:49 -08001962 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001963 HashSet<String> mQueue;
1964
Christopher Tate44a27902010-01-27 17:15:49 -08001965 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001966 mQueue = transportNames;
1967 }
1968
Christopher Tate4cc86e12009-09-21 19:36:51 -07001969 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001970 try {
1971 for (String transportName : mQueue) {
1972 IBackupTransport transport = getTransport(transportName);
1973 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001974 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001975 continue;
1976 }
1977
Joe Onorato8a9b2202010-02-26 18:56:32 -08001978 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001979 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001980 long startRealtime = SystemClock.elapsedRealtime();
1981 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001982
Christopher Tate4cc86e12009-09-21 19:36:51 -07001983 if (status == BackupConstants.TRANSPORT_OK) {
1984 status = transport.finishBackup();
1985 }
1986
1987 // Okay, the wipe really happened. Clean up our local bookkeeping.
1988 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001989 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001990 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001991 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001992 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001993 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001994 synchronized (mQueueLock) {
1995 recordInitPendingLocked(false, transportName);
1996 }
Dan Egnor726247c2009-09-29 19:12:31 -07001997 } else {
1998 // If this didn't work, requeue this one and try again
1999 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002000 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002001 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002002 synchronized (mQueueLock) {
2003 recordInitPendingLocked(true, transportName);
2004 }
2005 // do this via another alarm to make sure of the wakelock states
2006 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002007 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002008 + transportName + " resched in " + delay);
2009 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2010 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002011 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002012 }
2013 } catch (RemoteException e) {
2014 // can't happen; the transports are local
2015 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002016 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002017 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002018 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002019 mWakelock.release();
2020 }
2021 }
2022 }
2023
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002024 private void dataChangedImpl(String packageName) {
2025 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2026 dataChangedImpl(packageName, targets);
2027 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002028
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002029 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002030 // Record that we need a backup pass for the caller. Since multiple callers
2031 // may share a uid, we need to note all candidates within that uid and schedule
2032 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002033 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002034
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002035 if (targets == null) {
2036 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2037 + " uid=" + Binder.getCallingUid());
2038 return;
2039 }
2040
2041 synchronized (mQueueLock) {
2042 // Note that this client has made data changes that need to be backed up
2043 for (ApplicationInfo app : targets) {
2044 // validate the caller-supplied package name against the known set of
2045 // packages associated with this uid
2046 if (app.packageName.equals(packageName)) {
2047 // Add the caller to the set of pending backups. If there is
2048 // one already there, then overwrite it, but no harm done.
2049 BackupRequest req = new BackupRequest(app, false);
2050 if (mPendingBackups.put(app, req) == null) {
2051 // Journal this request in case of crash. The put()
2052 // operation returned null when this package was not already
2053 // in the set; we want to avoid touching the disk redundantly.
2054 writeToJournalLocked(packageName);
2055
2056 if (DEBUG) {
2057 int numKeys = mPendingBackups.size();
2058 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2059 for (BackupRequest b : mPendingBackups.values()) {
2060 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2061 }
2062 }
2063 }
2064 }
2065 }
2066 }
2067 }
2068
2069 // Note: packageName is currently unused, but may be in the future
2070 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002071 // If the caller does not hold the BACKUP permission, it can only request a
2072 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002073 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002074 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002075 synchronized (mBackupParticipants) {
2076 return mBackupParticipants.get(Binder.getCallingUid());
2077 }
2078 }
2079
2080 // a caller with full permission can ask to back up any participating app
2081 // !!! TODO: allow backup of ANY app?
2082 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2083 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002084 int N = mBackupParticipants.size();
2085 for (int i = 0; i < N; i++) {
2086 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2087 if (s != null) {
2088 targets.addAll(s);
2089 }
2090 }
2091 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002092 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002093 }
Christopher Tate46758122009-05-06 11:22:00 -07002094
Christopher Tatecde87f42009-06-12 12:55:53 -07002095 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002096 RandomAccessFile out = null;
2097 try {
2098 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2099 out = new RandomAccessFile(mJournal, "rws");
2100 out.seek(out.length());
2101 out.writeUTF(str);
2102 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002103 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002104 mJournal = null;
2105 } finally {
2106 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002107 }
2108 }
2109
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002110 // ----- IBackupManager binder interface -----
2111
2112 public void dataChanged(final String packageName) {
2113 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2114 if (targets == null) {
2115 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2116 + " uid=" + Binder.getCallingUid());
2117 return;
2118 }
2119
2120 mBackupHandler.post(new Runnable() {
2121 public void run() {
2122 dataChangedImpl(packageName, targets);
2123 }
2124 });
2125 }
2126
Christopher Tateee0e78a2009-07-02 11:17:03 -07002127 // Clear the given package's backup data from the current transport
2128 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002129 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002130 PackageInfo info;
2131 try {
2132 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2133 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002134 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002135 return;
2136 }
2137
2138 // If the caller does not hold the BACKUP permission, it can only request a
2139 // wipe of its own backed-up data.
2140 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002141 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002142 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2143 apps = mBackupParticipants.get(Binder.getCallingUid());
2144 } else {
2145 // a caller with full permission can ask to back up any participating app
2146 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002147 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002148 apps = new HashSet<ApplicationInfo>();
2149 int N = mBackupParticipants.size();
2150 for (int i = 0; i < N; i++) {
2151 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2152 if (s != null) {
2153 apps.addAll(s);
2154 }
2155 }
2156 }
2157
2158 // now find the given package in the set of candidate apps
2159 for (ApplicationInfo app : apps) {
2160 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002161 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002162 // found it; fire off the clear request
2163 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002164 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002165 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002166 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2167 new ClearParams(getTransport(mCurrentTransport), info));
2168 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002169 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002170 }
2171 break;
2172 }
2173 }
2174 }
2175
Christopher Tateace7f092009-06-15 18:07:25 -07002176 // Run a backup pass immediately for any applications that have declared
2177 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002178 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002180
Joe Onorato8a9b2202010-02-26 18:56:32 -08002181 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002182 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002183 // Because the alarms we are using can jitter, and we want an *immediate*
2184 // backup pass to happen, we restart the timer beginning with "next time,"
2185 // then manually fire the backup trigger intent ourselves.
2186 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002187 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002188 mRunBackupIntent.send();
2189 } catch (PendingIntent.CanceledException e) {
2190 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002191 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002192 }
Christopher Tate46758122009-05-06 11:22:00 -07002193 }
2194 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002195
Christopher Tate8031a3d2009-07-06 16:36:05 -07002196 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002197 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002198 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2199 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002200
Joe Onorato8a9b2202010-02-26 18:56:32 -08002201 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002202
Christopher Tate6ef58a12009-06-29 14:56:28 -07002203 boolean wasEnabled = mEnabled;
2204 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002205 Settings.Secure.putInt(mContext.getContentResolver(),
2206 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002207 mEnabled = enable;
2208 }
2209
Christopher Tate49401dd2009-07-01 12:34:29 -07002210 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002211 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002212 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002213 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002214 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002215 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002216 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002217
Christopher Tateb6787f22009-07-02 17:40:45 -07002218 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002219
2220 // This also constitutes an opt-out, so we wipe any data for
2221 // this device from the backend. We start that process with
2222 // an alarm in order to guarantee wakelock states.
2223 if (wasEnabled && mProvisioned) {
2224 // NOTE: we currently flush every registered transport, not just
2225 // the currently-active one.
2226 HashSet<String> allTransports;
2227 synchronized (mTransports) {
2228 allTransports = new HashSet<String>(mTransports.keySet());
2229 }
2230 // build the set of transports for which we are posting an init
2231 for (String transport : allTransports) {
2232 recordInitPendingLocked(true, transport);
2233 }
2234 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2235 mRunInitIntent);
2236 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002237 }
2238 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002239 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002240
Christopher Tatecce9da52010-02-03 15:11:15 -08002241 // Enable/disable automatic restore of app data at install time
2242 public void setAutoRestore(boolean doAutoRestore) {
2243 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2244 "setBackupEnabled");
2245
Joe Onorato8a9b2202010-02-26 18:56:32 -08002246 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002247
2248 synchronized (this) {
2249 Settings.Secure.putInt(mContext.getContentResolver(),
2250 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2251 mAutoRestore = doAutoRestore;
2252 }
2253 }
2254
Christopher Tate8031a3d2009-07-06 16:36:05 -07002255 // Mark the backup service as having been provisioned
2256 public void setBackupProvisioned(boolean available) {
2257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2258 "setBackupProvisioned");
2259
2260 boolean wasProvisioned = mProvisioned;
2261 synchronized (this) {
2262 Settings.Secure.putInt(mContext.getContentResolver(),
2263 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2264 mProvisioned = available;
2265 }
2266
2267 synchronized (mQueueLock) {
2268 if (available && !wasProvisioned && mEnabled) {
2269 // we're now good to go, so start the backup alarms
2270 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2271 } else if (!available) {
2272 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002273 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002274 mAlarmManager.cancel(mRunBackupIntent);
2275 }
2276 }
2277 }
2278
2279 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002280 // We used to use setInexactRepeating(), but that may be linked to
2281 // backups running at :00 more often than not, creating load spikes.
2282 // Schedule at an exact time for now, and also add a bit of "fuzz".
2283
2284 Random random = new Random();
2285 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2286 random.nextInt(FUZZ_MILLIS);
2287 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2288 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002289 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002290 }
2291
Christopher Tate6ef58a12009-06-29 14:56:28 -07002292 // Report whether the backup mechanism is currently enabled
2293 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002294 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002295 return mEnabled; // no need to synchronize just to read it
2296 }
2297
Christopher Tate91717492009-06-26 21:07:13 -07002298 // Report the name of the currently active transport
2299 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002300 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002301 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002302 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002303 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002304 }
2305
Christopher Tate91717492009-06-26 21:07:13 -07002306 // Report all known, available backup transports
2307 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002308 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002309
Christopher Tate91717492009-06-26 21:07:13 -07002310 String[] list = null;
2311 ArrayList<String> known = new ArrayList<String>();
2312 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2313 if (entry.getValue() != null) {
2314 known.add(entry.getKey());
2315 }
2316 }
2317
2318 if (known.size() > 0) {
2319 list = new String[known.size()];
2320 known.toArray(list);
2321 }
2322 return list;
2323 }
2324
2325 // Select which transport to use for the next backup operation. If the given
2326 // name is not one of the available transports, no action is taken and the method
2327 // returns null.
2328 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002329 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002330
2331 synchronized (mTransports) {
2332 String prevTransport = null;
2333 if (mTransports.get(transport) != null) {
2334 prevTransport = mCurrentTransport;
2335 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002336 Settings.Secure.putString(mContext.getContentResolver(),
2337 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002338 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002339 + " returning " + prevTransport);
2340 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002341 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002342 }
2343 return prevTransport;
2344 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002345 }
2346
2347 // Callback: a requested backup agent has been instantiated. This should only
2348 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002349 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002350 synchronized(mAgentConnectLock) {
2351 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002352 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002353 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2354 mConnectedAgent = agent;
2355 mConnecting = false;
2356 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002357 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002358 + " claiming agent connected");
2359 }
2360 mAgentConnectLock.notifyAll();
2361 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002362 }
2363
2364 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2365 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002366 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002367 public void agentDisconnected(String packageName) {
2368 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002369 synchronized(mAgentConnectLock) {
2370 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2371 mConnectedAgent = null;
2372 mConnecting = false;
2373 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002374 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002375 + " claiming agent disconnected");
2376 }
2377 mAgentConnectLock.notifyAll();
2378 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002379 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002380
Christopher Tate1bb69062010-02-19 17:02:12 -08002381 // An application being installed will need a restore pass, then the Package Manager
2382 // will need to be told when the restore is finished.
2383 public void restoreAtInstall(String packageName, int token) {
2384 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002385 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002386 + " attemping install-time restore");
2387 return;
2388 }
2389
2390 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002391 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002392 + " token=" + Integer.toHexString(token));
2393
Christopher Tatef0872722010-02-25 15:22:48 -08002394 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002395 // okay, we're going to attempt a restore of this package from this restore set.
2396 // The eventual message back into the Package Manager to run the post-install
2397 // steps for 'token' will be issued from the restore handling code.
2398
2399 // We can use a synthetic PackageInfo here because:
2400 // 1. We know it's valid, since the Package Manager supplied the name
2401 // 2. Only the packageName field will be used by the restore code
2402 PackageInfo pkg = new PackageInfo();
2403 pkg.packageName = packageName;
2404
2405 mWakelock.acquire();
2406 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2407 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002408 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002409 mBackupHandler.sendMessage(msg);
2410 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002411 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2412 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002413 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002414 try {
2415 mPackageManagerBinder.finishPackageInstall(token);
2416 } catch (RemoteException e) { /* can't happen */ }
2417 }
2418 }
2419
Christopher Tate8c850b72009-06-07 19:33:20 -07002420 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002421 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2422 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2423 + " transport=" + transport);
2424
2425 boolean needPermission = true;
2426 if (transport == null) {
2427 transport = mCurrentTransport;
2428
2429 if (packageName != null) {
2430 PackageInfo app = null;
2431 try {
2432 app = mPackageManager.getPackageInfo(packageName, 0);
2433 } catch (NameNotFoundException nnf) {
2434 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2435 throw new IllegalArgumentException("Package " + packageName + " not found");
2436 }
2437
2438 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2439 // So: using the current active transport, and the caller has asked
2440 // that its own package will be restored. In this narrow use case
2441 // we do not require the caller to hold the permission.
2442 needPermission = false;
2443 }
2444 }
2445 }
2446
2447 if (needPermission) {
2448 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2449 "beginRestoreSession");
2450 } else {
2451 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2452 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002453
2454 synchronized(this) {
2455 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002456 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002457 return null;
2458 }
Chris Tate44ab8452010-11-16 15:10:49 -08002459 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002460 }
2461 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002462 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002463
Christopher Tate44a27902010-01-27 17:15:49 -08002464 // Note that a currently-active backup agent has notified us that it has
2465 // completed the given outstanding asynchronous backup/restore operation.
2466 public void opComplete(int token) {
2467 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002468 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002469 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2470 mCurrentOpLock.notifyAll();
2471 }
2472 }
2473
Christopher Tate9b3905c2009-06-08 15:24:01 -07002474 // ----- Restore session -----
2475
Christopher Tate80202c82010-01-25 19:37:47 -08002476 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002477 private static final String TAG = "RestoreSession";
2478
Chris Tate44ab8452010-11-16 15:10:49 -08002479 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07002480 private IBackupTransport mRestoreTransport = null;
2481 RestoreSet[] mRestoreSets = null;
2482
Chris Tate44ab8452010-11-16 15:10:49 -08002483 ActiveRestoreSession(String packageName, String transport) {
2484 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07002485 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002486 }
2487
2488 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002489 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002490 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002491 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002492 if (observer == null) {
2493 throw new IllegalArgumentException("Observer must not be null");
2494 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002495
Christopher Tate1bb69062010-02-19 17:02:12 -08002496 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002497 try {
Christopher Tate43383042009-07-13 15:17:13 -07002498 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002499 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002500 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002501 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002502 // spin off the transport request to our service thread
2503 mWakelock.acquire();
2504 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2505 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2506 mBackupHandler.sendMessage(msg);
2507 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002508 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002509 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002510 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002511 } finally {
2512 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002513 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002514 }
2515
Christopher Tate84725812010-02-04 15:52:40 -08002516 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002517 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2518 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002519
Chris Tate44ab8452010-11-16 15:10:49 -08002520 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002521 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002522
Dan Egnor0084da52009-07-29 12:57:16 -07002523 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08002524 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
2525 return -1;
2526 }
2527
2528 if (mPackageName != null) {
2529 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07002530 return -1;
2531 }
2532
Christopher Tate21ab6a52009-09-24 18:01:46 -07002533 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002534 for (int i = 0; i < mRestoreSets.length; i++) {
2535 if (token == mRestoreSets[i].token) {
2536 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002537 mWakelock.acquire();
2538 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002539 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07002540 mBackupHandler.sendMessage(msg);
2541 Binder.restoreCallingIdentity(oldId);
2542 return 0;
2543 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002544 }
2545 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002546
Joe Onorato8a9b2202010-02-26 18:56:32 -08002547 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002548 return -1;
2549 }
2550
Christopher Tate84725812010-02-04 15:52:40 -08002551 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002552 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002553
Chris Tate44ab8452010-11-16 15:10:49 -08002554 if (mPackageName != null) {
2555 if (! mPackageName.equals(packageName)) {
2556 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
2557 + " on session for package " + mPackageName);
2558 return -1;
2559 }
2560 }
2561
Christopher Tate84725812010-02-04 15:52:40 -08002562 PackageInfo app = null;
2563 try {
2564 app = mPackageManager.getPackageInfo(packageName, 0);
2565 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002566 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002567 return -1;
2568 }
2569
2570 // If the caller is not privileged and is not coming from the target
2571 // app's uid, throw a permission exception back to the caller.
2572 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2573 Binder.getCallingPid(), Binder.getCallingUid());
2574 if ((perm == PackageManager.PERMISSION_DENIED) &&
2575 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002576 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002577 + " or calling uid=" + Binder.getCallingUid());
2578 throw new SecurityException("No permission to restore other packages");
2579 }
2580
Christopher Tate7d411a32010-02-26 11:27:08 -08002581 // If the package has no backup agent, we obviously cannot proceed
2582 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002583 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002584 return -1;
2585 }
2586
Christopher Tate84725812010-02-04 15:52:40 -08002587 // So far so good; we're allowed to try to restore this package. Now
2588 // check whether there is data for it in the current dataset, falling back
2589 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002590 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002591
2592 // If we didn't come up with a place to look -- no ancestral dataset and
2593 // the app has never been backed up from this device -- there's nothing
2594 // to do but return failure.
2595 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08002596 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08002597 return -1;
2598 }
2599
2600 // Ready to go: enqueue the restore request and claim success
2601 long oldId = Binder.clearCallingIdentity();
2602 mWakelock.acquire();
2603 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07002604 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08002605 mBackupHandler.sendMessage(msg);
2606 Binder.restoreCallingIdentity(oldId);
2607 return 0;
2608 }
2609
Dan Egnor0084da52009-07-29 12:57:16 -07002610 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002611 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002612
Dan Egnor0084da52009-07-29 12:57:16 -07002613 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002614 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002615 try {
2616 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2617 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002618 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002619 } finally {
2620 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002621 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002622 }
2623 }
2624
2625 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002626 if (BackupManagerService.this.mActiveRestoreSession == this) {
2627 BackupManagerService.this.mActiveRestoreSession = null;
2628 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002629 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002630 }
2631 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002632 }
2633 }
2634
Christopher Tate043dadc2009-06-02 16:11:00 -07002635
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002636 @Override
2637 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2638 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002639 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002640 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002641 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002642 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002643 pw.println("Last backup pass: " + mLastBackupPass
2644 + " (now = " + System.currentTimeMillis() + ')');
2645 pw.println(" next scheduled: " + mNextBackupPass);
2646
Christopher Tate91717492009-06-26 21:07:13 -07002647 pw.println("Available transports:");
2648 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002649 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2650 try {
2651 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2652 for (File f : dir.listFiles()) {
2653 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2654 }
2655 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002656 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002657 pw.println(" Error: " + e);
2658 }
Christopher Tate91717492009-06-26 21:07:13 -07002659 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002660
2661 pw.println("Pending init: " + mPendingInits.size());
2662 for (String s : mPendingInits) {
2663 pw.println(" " + s);
2664 }
2665
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002666 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002667 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002668 for (int i=0; i<N; i++) {
2669 int uid = mBackupParticipants.keyAt(i);
2670 pw.print(" uid: ");
2671 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002672 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2673 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002674 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002675 }
2676 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002677
Christopher Tateb49ceb32010-02-08 16:22:24 -08002678 pw.println("Ancestral packages: "
2679 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002680 if (mAncestralPackages != null) {
2681 for (String pkg : mAncestralPackages) {
2682 pw.println(" " + pkg);
2683 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002684 }
2685
Christopher Tate73e02522009-07-15 14:18:26 -07002686 pw.println("Ever backed up: " + mEverStoredApps.size());
2687 for (String pkg : mEverStoredApps) {
2688 pw.println(" " + pkg);
2689 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002690
2691 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002692 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002693 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002694 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002695 }
2696 }
Christopher Tate487529a2009-04-29 14:03:25 -07002697}