blob: a334dbbb833bac2b0cb34a78f5a594ebffccc835 [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 Tate4a627c72011-04-01 14:43:32 -070026import android.app.backup.BackupDataOutput;
27import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060028import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080029import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070030import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080031import android.app.backup.IRestoreObserver;
32import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070033import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070036import android.content.Context;
37import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070039import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070040import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070041import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080042import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070043import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070044import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060045import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060046import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070047import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070049import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070050import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080052import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080054import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070057import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070058import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070060import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070061import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080062import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070063import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080066import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070067import android.util.StringBuilderPrinter;
68
69import libcore.io.Libcore;
Christopher Tate487529a2009-04-29 14:03:25 -070070
Jason parksa3cdaa52011-01-13 14:15:43 -060071import com.android.internal.backup.BackupConstants;
72import com.android.internal.backup.IBackupTransport;
73import com.android.internal.backup.LocalTransport;
74import com.android.server.PackageManagerBackupAgent.Metadata;
75
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070077import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070078import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080079import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070080import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070081import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070082import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070083import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040084import java.util.ArrayList;
85import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070086import java.util.HashSet;
87import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070088import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070089import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080090import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -070091import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate487529a2009-04-29 14:03:25 -070092
93class BackupManagerService extends IBackupManager.Stub {
94 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -070095 private static final boolean DEBUG = true;
96
97 // Name and current contents version of the full-backup manifest file
98 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
99 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -0700100
Christopher Tate49401dd2009-07-01 12:34:29 -0700101 // How often we perform a backup pass. Privileged external callers can
102 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700103 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700104
Dan Egnorc1c49c02009-10-30 17:35:39 -0700105 // Random variation in backup scheduling time to avoid server load spikes
106 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
107
Christopher Tate8031a3d2009-07-06 16:36:05 -0700108 // The amount of time between the initial provisioning of the device and
109 // the first backup pass.
110 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
111
Christopher Tate45281862010-03-05 15:46:30 -0800112 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
113 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
114 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700115 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700116 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700117 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700118 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700119 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700120 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
121 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800122 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700123 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
124 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700125
126 // Timeout interval for deciding that a bind or clear-data has taken too long
127 static final long TIMEOUT_INTERVAL = 10 * 1000;
128
Christopher Tate44a27902010-01-27 17:15:49 -0800129 // Timeout intervals for agent backup & restore operations
130 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700131 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800132 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
133
Christopher Tate4a627c72011-04-01 14:43:32 -0700134 // User confirmation timeout for a full backup/restore operation
135 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
136
Christopher Tate487529a2009-04-29 14:03:25 -0700137 private Context mContext;
138 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700140 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700141 private PowerManager mPowerManager;
142 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800143 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700144
Christopher Tate73e02522009-07-15 14:18:26 -0700145 boolean mEnabled; // access to this is synchronized on 'this'
146 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800147 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700148 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800149 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
150 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700151 PendingIntent mRunBackupIntent, mRunInitIntent;
152 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700153 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700154 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700155 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700156 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700157 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700158 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700159
Christopher Tate4a627c72011-04-01 14:43:32 -0700160 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700161 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700162 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700163
164 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700165 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700166 }
Christopher Tate46758122009-05-06 11:22:00 -0700167 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800168 // Backups that we haven't started yet. Keys are package names.
169 HashMap<String,BackupRequest> mPendingBackups
170 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700171
172 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700173 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700174
175 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700176 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700177
Christopher Tate043dadc2009-06-02 16:11:00 -0700178 // The thread performing the sequence of queued backups binds to each app's agent
179 // in succession. Bind notifications are asynchronously delivered through the
180 // Activity Manager; use this lock object to signal when a requested binding has
181 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700182 final Object mAgentConnectLock = new Object();
183 IBackupAgent mConnectedAgent;
184 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700185 volatile long mLastBackupPass;
186 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700187
Christopher Tate55f931a2009-09-29 17:17:34 -0700188 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700189 final Object mClearDataLock = new Object();
190 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700191
Christopher Tate91717492009-06-26 21:07:13 -0700192 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700193 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700194 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700195 String mCurrentTransport;
196 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800197 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700198
Christopher Tate2d449afe2010-03-29 19:14:24 -0700199 class RestoreGetSetsParams {
200 public IBackupTransport transport;
201 public ActiveRestoreSession session;
202 public IRestoreObserver observer;
203
204 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
205 IRestoreObserver _observer) {
206 transport = _transport;
207 session = _session;
208 observer = _observer;
209 }
210 }
211
Christopher Tate73e02522009-07-15 14:18:26 -0700212 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700213 public IBackupTransport transport;
214 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700215 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800216 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800217 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700218 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800219
220 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700221 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800222 transport = _transport;
223 observer = _obs;
224 token = _token;
225 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800226 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700227 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800228 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700229
Chris Tate249345b2010-10-29 12:57:04 -0700230 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
231 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700232 transport = _transport;
233 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700234 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800235 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800236 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700237 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700238 }
239 }
240
Christopher Tate73e02522009-07-15 14:18:26 -0700241 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700242 public IBackupTransport transport;
243 public PackageInfo packageInfo;
244
245 ClearParams(IBackupTransport _transport, PackageInfo _info) {
246 transport = _transport;
247 packageInfo = _info;
248 }
249 }
250
Christopher Tate4a627c72011-04-01 14:43:32 -0700251 class FullParams {
252 public ParcelFileDescriptor fd;
253 public final AtomicBoolean latch;
254 public IFullBackupRestoreObserver observer;
255
256 FullParams() {
257 latch = new AtomicBoolean(false);
258 }
259 }
260
261 class FullBackupParams extends FullParams {
262 public boolean includeApks;
263 public boolean includeShared;
264 public boolean allApps;
265 public String[] packages;
266
267 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
268 boolean doAllApps, String[] pkgList) {
269 fd = output;
270 includeApks = saveApks;
271 includeShared = saveShared;
272 allApps = doAllApps;
273 packages = pkgList;
274 }
275 }
276
277 class FullRestoreParams extends FullParams {
278 FullRestoreParams(ParcelFileDescriptor input) {
279 fd = input;
280 }
281 }
282
Christopher Tate44a27902010-01-27 17:15:49 -0800283 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
284 // token is the index of the entry in the pending-operations list.
285 static final int OP_PENDING = 0;
286 static final int OP_ACKNOWLEDGED = 1;
287 static final int OP_TIMEOUT = -1;
288
289 final SparseIntArray mCurrentOperations = new SparseIntArray();
290 final Object mCurrentOpLock = new Object();
291 final Random mTokenGenerator = new Random();
292
Christopher Tate4a627c72011-04-01 14:43:32 -0700293 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
294
Christopher Tate5cb400b2009-06-25 16:03:14 -0700295 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700296 File mBaseStateDir;
297 File mDataDir;
298 File mJournalDir;
299 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700300
Christopher Tate84725812010-02-04 15:52:40 -0800301 // Keep a log of all the apps we've ever backed up, and what the
302 // dataset tokens are for both the current backup dataset and
303 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700304 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700305 HashSet<String> mEverStoredApps = new HashSet<String>();
306
Christopher Tateb49ceb32010-02-08 16:22:24 -0800307 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800308 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800309 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800310 long mAncestralToken = 0;
311 long mCurrentToken = 0;
312
Christopher Tate4cc86e12009-09-21 19:36:51 -0700313 // Persistently track the need to do a full init
314 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
315 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700316
Christopher Tate4a627c72011-04-01 14:43:32 -0700317 // Utility: build a new random integer token
318 int generateToken() {
319 int token;
320 do {
321 synchronized (mTokenGenerator) {
322 token = mTokenGenerator.nextInt();
323 }
324 } while (token < 0);
325 return token;
326 }
327
Christopher Tate44a27902010-01-27 17:15:49 -0800328 // ----- Asynchronous backup/restore handler thread -----
329
330 private class BackupHandler extends Handler {
331 public BackupHandler(Looper looper) {
332 super(looper);
333 }
334
335 public void handleMessage(Message msg) {
336
337 switch (msg.what) {
338 case MSG_RUN_BACKUP:
339 {
340 mLastBackupPass = System.currentTimeMillis();
341 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
342
343 IBackupTransport transport = getTransport(mCurrentTransport);
344 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800345 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800346 mWakelock.release();
347 break;
348 }
349
350 // snapshot the pending-backup set and work on that
351 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800352 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800353 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800354 // Do we have any work to do? Construct the work queue
355 // then release the synchronization lock to actually run
356 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800357 if (mPendingBackups.size() > 0) {
358 for (BackupRequest b: mPendingBackups.values()) {
359 queue.add(b);
360 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800361 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800362 mPendingBackups.clear();
363
364 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800365 mJournal = null;
366
Christopher Tate44a27902010-01-27 17:15:49 -0800367 }
368 }
Christopher Tatec61da312010-02-05 10:41:27 -0800369
370 if (queue.size() > 0) {
371 // At this point, we have started a new journal file, and the old
372 // file identity is being passed to the backup processing thread.
373 // When it completes successfully, that old journal file will be
374 // deleted. If we crash prior to that, the old journal is parsed
375 // at next boot and the journaled requests fulfilled.
376 (new PerformBackupTask(transport, queue, oldJournal)).run();
377 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800378 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800379 mWakelock.release();
380 }
Christopher Tate44a27902010-01-27 17:15:49 -0800381 break;
382 }
383
384 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700385 {
386 FullBackupParams params = (FullBackupParams)msg.obj;
387 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
388 params.includeShared, params.allApps, params.packages,
389 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800390 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700391 }
Christopher Tate44a27902010-01-27 17:15:49 -0800392
393 case MSG_RUN_RESTORE:
394 {
395 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800396 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800397 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700398 params.token, params.pkgInfo, params.pmToken,
399 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800400 break;
401 }
402
403 case MSG_RUN_CLEAR:
404 {
405 ClearParams params = (ClearParams)msg.obj;
406 (new PerformClearTask(params.transport, params.packageInfo)).run();
407 break;
408 }
409
410 case MSG_RUN_INITIALIZE:
411 {
412 HashSet<String> queue;
413
414 // Snapshot the pending-init queue and work on that
415 synchronized (mQueueLock) {
416 queue = new HashSet<String>(mPendingInits);
417 mPendingInits.clear();
418 }
419
420 (new PerformInitializeTask(queue)).run();
421 break;
422 }
423
Christopher Tate2d449afe2010-03-29 19:14:24 -0700424 case MSG_RUN_GET_RESTORE_SETS:
425 {
426 // Like other async operations, this is entered with the wakelock held
427 RestoreSet[] sets = null;
428 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
429 try {
430 sets = params.transport.getAvailableRestoreSets();
431 // cache the result in the active session
432 synchronized (params.session) {
433 params.session.mRestoreSets = sets;
434 }
435 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
436 } catch (Exception e) {
437 Slog.e(TAG, "Error from transport getting set list");
438 } finally {
439 if (params.observer != null) {
440 try {
441 params.observer.restoreSetsAvailable(sets);
442 } catch (RemoteException re) {
443 Slog.e(TAG, "Unable to report listing to observer");
444 } catch (Exception e) {
445 Slog.e(TAG, "Restore observer threw", e);
446 }
447 }
448
Christopher Tate2a935092011-03-03 17:30:32 -0800449 // Done: reset the session timeout clock
450 removeMessages(MSG_RESTORE_TIMEOUT);
451 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
452
Christopher Tate2d449afe2010-03-29 19:14:24 -0700453 mWakelock.release();
454 }
455 break;
456 }
457
Christopher Tate44a27902010-01-27 17:15:49 -0800458 case MSG_TIMEOUT:
459 {
460 synchronized (mCurrentOpLock) {
461 final int token = msg.arg1;
462 int state = mCurrentOperations.get(token, OP_TIMEOUT);
463 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800464 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800465 mCurrentOperations.put(token, OP_TIMEOUT);
466 }
467 mCurrentOpLock.notifyAll();
468 }
469 break;
470 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800471
472 case MSG_RESTORE_TIMEOUT:
473 {
474 synchronized (BackupManagerService.this) {
475 if (mActiveRestoreSession != null) {
476 // Client app left the restore session dangling. We know that it
477 // can't be in the middle of an actual restore operation because
478 // those are executed serially on this same handler thread. Clean
479 // up now.
480 Slog.w(TAG, "Restore session timed out; aborting");
481 post(mActiveRestoreSession.new EndRestoreRunnable(
482 BackupManagerService.this, mActiveRestoreSession));
483 }
484 }
485 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700486
487 case MSG_FULL_CONFIRMATION_TIMEOUT:
488 {
489 synchronized (mFullConfirmations) {
490 FullParams params = mFullConfirmations.get(msg.arg1);
491 if (params != null) {
492 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
493
494 // Release the waiter; timeout == completion
495 signalFullBackupRestoreCompletion(params);
496
497 // Remove the token from the set
498 mFullConfirmations.delete(msg.arg1);
499
500 // Report a timeout to the observer, if any
501 if (params.observer != null) {
502 try {
503 params.observer.onTimeout();
504 } catch (RemoteException e) {
505 /* don't care if the app has gone away */
506 }
507 }
508 } else {
509 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
510 }
511 }
512 break;
513 }
Christopher Tate44a27902010-01-27 17:15:49 -0800514 }
515 }
516 }
517
518 // ----- Main service implementation -----
519
Christopher Tate487529a2009-04-29 14:03:25 -0700520 public BackupManagerService(Context context) {
521 mContext = context;
522 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700523 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700524 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700525
Christopher Tateb6787f22009-07-02 17:40:45 -0700526 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
527 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
528
Christopher Tate44a27902010-01-27 17:15:49 -0800529 mBackupManagerBinder = asInterface(asBinder());
530
531 // spin up the backup/restore handler thread
532 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
533 mHandlerThread.start();
534 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
535
Christopher Tate22b87872009-05-04 16:41:53 -0700536 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700537 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700538 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700539 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700540 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800541 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800542 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800543 // If Encrypted file systems is enabled or disabled, this call will return the
544 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600545 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800546 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700547 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700548
Christopher Tate4cc86e12009-09-21 19:36:51 -0700549 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700550 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700551 IntentFilter filter = new IntentFilter();
552 filter.addAction(RUN_BACKUP_ACTION);
553 context.registerReceiver(mRunBackupReceiver, filter,
554 android.Manifest.permission.BACKUP, null);
555
556 mRunInitReceiver = new RunInitializeReceiver();
557 filter = new IntentFilter();
558 filter.addAction(RUN_INITIALIZE_ACTION);
559 context.registerReceiver(mRunInitReceiver, filter,
560 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700561
562 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700563 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
564 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
565
Christopher Tate4cc86e12009-09-21 19:36:51 -0700566 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
567 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
568 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
569
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700571 mJournalDir = new File(mBaseStateDir, "pending");
572 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700573 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700574
Christopher Tate73e02522009-07-15 14:18:26 -0700575 // Set up the various sorts of package tracking we do
576 initPackageTracking();
577
Christopher Tateabce4e82009-06-18 18:35:32 -0700578 // Build our mapping of uid to backup client services. This implicitly
579 // schedules a backup pass on the Package Manager metadata the first
580 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700581 synchronized (mBackupParticipants) {
582 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700583 }
584
Dan Egnor87a02bc2009-06-17 02:30:10 -0700585 // Set up our transport options and initialize the default transport
586 // TODO: Have transports register themselves somehow?
587 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700588 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700589 ComponentName localName = new ComponentName(context, LocalTransport.class);
590 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700591
Christopher Tate91717492009-06-26 21:07:13 -0700592 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700593 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
594 Settings.Secure.BACKUP_TRANSPORT);
595 if ("".equals(mCurrentTransport)) {
596 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700597 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800598 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700599
600 // Attach to the Google backup transport. When this comes up, it will set
601 // itself as the current transport because we explicitly reset mCurrentTransport
602 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700603 ComponentName transportComponent = new ComponentName("com.google.android.backup",
604 "com.google.android.backup.BackupTransportService");
605 try {
606 // If there's something out there that is supposed to be the Google
607 // backup transport, make sure it's legitimately part of the OS build
608 // and not an app lying about its package name.
609 ApplicationInfo info = mPackageManager.getApplicationInfo(
610 transportComponent.getPackageName(), 0);
611 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
612 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
613 Intent intent = new Intent().setComponent(transportComponent);
614 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
615 } else {
616 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
617 }
618 } catch (PackageManager.NameNotFoundException nnf) {
619 // No such package? No binding.
620 if (DEBUG) Slog.v(TAG, "Google transport not present");
621 }
Christopher Tateaa088442009-06-16 18:25:46 -0700622
Christopher Tatecde87f42009-06-12 12:55:53 -0700623 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700624 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700625 parseLeftoverJournals();
626
Christopher Tateb6787f22009-07-02 17:40:45 -0700627 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700628 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700629
630 // Start the backup passes going
631 setBackupEnabled(areEnabled);
632 }
633
634 private class RunBackupReceiver extends BroadcastReceiver {
635 public void onReceive(Context context, Intent intent) {
636 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700637 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700638 if (mPendingInits.size() > 0) {
639 // If there are pending init operations, we process those
640 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800641 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700642 try {
643 mAlarmManager.cancel(mRunInitIntent);
644 mRunInitIntent.send();
645 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800646 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700647 // can't really do more than bail here
648 }
649 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800650 // Don't run backups now if we're disabled or not yet
651 // fully set up.
652 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700654
655 // Acquire the wakelock and pass it to the backup thread. it will
656 // be released once backup concludes.
657 mWakelock.acquire();
658
659 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
660 mBackupHandler.sendMessage(msg);
661 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800662 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700663 }
664 }
665 }
666 }
667 }
668 }
669
670 private class RunInitializeReceiver extends BroadcastReceiver {
671 public void onReceive(Context context, Intent intent) {
672 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
673 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675
676 // Acquire the wakelock and pass it to the init thread. it will
677 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700678 mWakelock.acquire();
679
Christopher Tate4cc86e12009-09-21 19:36:51 -0700680 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700681 mBackupHandler.sendMessage(msg);
682 }
683 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700684 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700685 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700686
Christopher Tate73e02522009-07-15 14:18:26 -0700687 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800688 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700689
Christopher Tate84725812010-02-04 15:52:40 -0800690 // Remember our ancestral dataset
691 mTokenFile = new File(mBaseStateDir, "ancestral");
692 try {
693 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800694 int version = tf.readInt();
695 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
696 mAncestralToken = tf.readLong();
697 mCurrentToken = tf.readLong();
698
699 int numPackages = tf.readInt();
700 if (numPackages >= 0) {
701 mAncestralPackages = new HashSet<String>();
702 for (int i = 0; i < numPackages; i++) {
703 String pkgName = tf.readUTF();
704 mAncestralPackages.add(pkgName);
705 }
706 }
707 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800708 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800709 } catch (FileNotFoundException fnf) {
710 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800711 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800712 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800713 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800714 }
715
Christopher Tatee97e8072009-07-15 16:45:50 -0700716 // Keep a log of what apps we've ever backed up. Because we might have
717 // rebooted in the middle of an operation that was removing something from
718 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700719 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700720 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700721
Christopher Tatee97e8072009-07-15 16:45:50 -0700722 // If we were in the middle of removing something from the ever-backed-up
723 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700724 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700725 if (tempProcessedFile.exists()) {
726 tempProcessedFile.delete();
727 }
728
Dan Egnor852f8e42009-09-30 11:20:45 -0700729 // If there are previous contents, parse them out then start a new
730 // file to continue the recordkeeping.
731 if (mEverStored.exists()) {
732 RandomAccessFile temp = null;
733 RandomAccessFile in = null;
734
735 try {
736 temp = new RandomAccessFile(tempProcessedFile, "rws");
737 in = new RandomAccessFile(mEverStored, "r");
738
739 while (true) {
740 PackageInfo info;
741 String pkg = in.readUTF();
742 try {
743 info = mPackageManager.getPackageInfo(pkg, 0);
744 mEverStoredApps.add(pkg);
745 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800746 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700747 } catch (NameNotFoundException e) {
748 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700750 }
751 }
752 } catch (EOFException e) {
753 // Once we've rewritten the backup history log, atomically replace the
754 // old one with the new one then reopen the file for continuing use.
755 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800756 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700757 }
758 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800759 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700760 } finally {
761 try { if (temp != null) temp.close(); } catch (IOException e) {}
762 try { if (in != null) in.close(); } catch (IOException e) {}
763 }
764 }
765
Christopher Tate73e02522009-07-15 14:18:26 -0700766 // Register for broadcasts about package install, etc., so we can
767 // update the provider list.
768 IntentFilter filter = new IntentFilter();
769 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
770 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
771 filter.addDataScheme("package");
772 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800773 // Register for events related to sdcard installation.
774 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800775 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
776 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800777 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700778 }
779
Christopher Tatecde87f42009-06-12 12:55:53 -0700780 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700781 for (File f : mJournalDir.listFiles()) {
782 if (mJournal == null || f.compareTo(mJournal) != 0) {
783 // This isn't the current journal, so it must be a leftover. Read
784 // out the package names mentioned there and schedule them for
785 // backup.
786 RandomAccessFile in = null;
787 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400788 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700789 in = new RandomAccessFile(f, "r");
790 while (true) {
791 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400792 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700793 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700794 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700795 } catch (EOFException e) {
796 // no more data; we're done
797 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800798 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700799 } finally {
800 // close/delete the file
801 try { if (in != null) in.close(); } catch (IOException e) {}
802 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700803 }
804 }
805 }
806 }
807
Christopher Tate4cc86e12009-09-21 19:36:51 -0700808 // Maintain persistent state around whether need to do an initialize operation.
809 // Must be called with the queue lock held.
810 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700812 + " on transport " + transportName);
813 try {
814 IBackupTransport transport = getTransport(transportName);
815 String transportDirName = transport.transportDirName();
816 File stateDir = new File(mBaseStateDir, transportDirName);
817 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
818
819 if (isPending) {
820 // We need an init before we can proceed with sending backup data.
821 // Record that with an entry in our set of pending inits, as well as
822 // journaling it via creation of a sentinel file.
823 mPendingInits.add(transportName);
824 try {
825 (new FileOutputStream(initPendingFile)).close();
826 } catch (IOException ioe) {
827 // Something is badly wrong with our permissions; just try to move on
828 }
829 } else {
830 // No more initialization needed; wipe the journal and reset our state.
831 initPendingFile.delete();
832 mPendingInits.remove(transportName);
833 }
834 } catch (RemoteException e) {
835 // can't happen; the transport is local
836 }
837 }
838
Christopher Tated55e18a2009-09-21 10:12:59 -0700839 // Reset all of our bookkeeping, in response to having been told that
840 // the backend data has been wiped [due to idle expiry, for example],
841 // so we must re-upload all saved settings.
842 void resetBackupState(File stateFileDir) {
843 synchronized (mQueueLock) {
844 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700845 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700846 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700847
Christopher Tate84725812010-02-04 15:52:40 -0800848 mCurrentToken = 0;
849 writeRestoreTokens();
850
Christopher Tated55e18a2009-09-21 10:12:59 -0700851 // Remove all the state files
852 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700853 // ... but don't touch the needs-init sentinel
854 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
855 sf.delete();
856 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700857 }
Christopher Tate45597642011-04-04 16:59:21 -0700858 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700859
Christopher Tate45597642011-04-04 16:59:21 -0700860 // Enqueue a new backup of every participant
861 int N = mBackupParticipants.size();
862 for (int i=0; i<N; i++) {
863 int uid = mBackupParticipants.keyAt(i);
864 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
865 for (ApplicationInfo app: participants) {
866 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700867 }
868 }
869 }
870
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800871 // Add a transport to our set of available backends. If 'transport' is null, this
872 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700873 private void registerTransport(String name, IBackupTransport transport) {
874 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800875 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800876 if (transport != null) {
877 mTransports.put(name, transport);
878 } else {
879 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800880 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800881 mCurrentTransport = null;
882 }
883 // Nothing further to do in the unregistration case
884 return;
885 }
Christopher Tate91717492009-06-26 21:07:13 -0700886 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700887
888 // If the init sentinel file exists, we need to be sure to perform the init
889 // as soon as practical. We also create the state directory at registration
890 // time to ensure it's present from the outset.
891 try {
892 String transportName = transport.transportDirName();
893 File stateDir = new File(mBaseStateDir, transportName);
894 stateDir.mkdirs();
895
896 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
897 if (initSentinel.exists()) {
898 synchronized (mQueueLock) {
899 mPendingInits.add(transportName);
900
901 // TODO: pick a better starting time than now + 1 minute
902 long delay = 1000 * 60; // one minute, in milliseconds
903 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
904 System.currentTimeMillis() + delay, mRunInitIntent);
905 }
906 }
907 } catch (RemoteException e) {
908 // can't happen, the transport is local
909 }
Christopher Tate91717492009-06-26 21:07:13 -0700910 }
911
Christopher Tate3799bc22009-05-06 16:13:56 -0700912 // ----- Track installation/removal of packages -----
913 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
914 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800915 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700916
Christopher Tate3799bc22009-05-06 16:13:56 -0700917 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800918 boolean replacing = false;
919 boolean added = false;
920 Bundle extras = intent.getExtras();
921 String pkgList[] = null;
922 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
923 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
924 Uri uri = intent.getData();
925 if (uri == null) {
926 return;
927 }
928 String pkgName = uri.getSchemeSpecificPart();
929 if (pkgName != null) {
930 pkgList = new String[] { pkgName };
931 }
932 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
933 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800934 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800935 added = true;
936 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800937 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800938 added = false;
939 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
940 }
941 if (pkgList == null || pkgList.length == 0) {
942 return;
943 }
944 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700945 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800946 for (String pkgName : pkgList) {
947 if (replacing) {
948 // The package was just upgraded
949 updatePackageParticipantsLocked(pkgName);
950 } else {
951 // The package was just added
952 addPackageParticipantsLocked(pkgName);
953 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700954 }
955 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800956 } else {
957 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700958 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
959 } else {
960 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800961 for (String pkgName : pkgList) {
962 removePackageParticipantsLocked(pkgName);
963 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700964 }
965 }
966 }
967 }
968 };
969
Dan Egnor87a02bc2009-06-17 02:30:10 -0700970 // ----- Track connection to GoogleBackupTransport service -----
971 ServiceConnection mGoogleConnection = new ServiceConnection() {
972 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800973 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700974 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700975 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700976 }
977
978 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800979 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700980 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700981 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700982 }
983 };
984
Christopher Tate181fafa2009-05-14 11:12:14 -0700985 // Add the backup agents in the given package to our set of known backup participants.
986 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700987 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700988 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700990 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700991 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700992 }
993
Christopher Tate181fafa2009-05-14 11:12:14 -0700994 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700995 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700996 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700998 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800999 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001000 + " uid=" + p.applicationInfo.uid
1001 + " killAfterRestore="
1002 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001003 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001004 }
1005 }
1006
Dan Egnorefe52642009-06-24 00:16:33 -07001007 for (PackageInfo pkg : targetPkgs) {
1008 if (packageName == null || pkg.packageName.equals(packageName)) {
1009 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001010 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001011 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001012 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001013 mBackupParticipants.put(uid, set);
1014 }
Dan Egnorefe52642009-06-24 00:16:33 -07001015 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001016
1017 // If we've never seen this app before, schedule a backup for it
1018 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001020 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001021 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001022 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001023 }
Christopher Tate487529a2009-04-29 14:03:25 -07001024 }
1025 }
1026
Christopher Tate6785dd82009-06-18 15:58:25 -07001027 // Remove the given package's entry from our known active set. If
1028 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001029 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001030 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001031 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001033 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001034 } else {
1035 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001036 List<PackageInfo> knownPackages = allAgentPackages();
1037 for (PackageInfo pkg : knownPackages) {
1038 allApps.add(pkg.packageName);
1039 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001040 }
1041 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001042 }
1043
Joe Onorato8ad02812009-05-13 01:41:44 -04001044 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001045 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001046 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001048 + ") removing " + allPackageNames.size() + " entries");
1049 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001050 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001051 }
1052 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001053 for (String pkg : allPackageNames) {
1054 if (packageName == null || pkg.equals(packageName)) {
1055 int uid = -1;
1056 try {
1057 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1058 uid = info.applicationInfo.uid;
1059 } catch (NameNotFoundException e) {
1060 // we don't know this package name, so just skip it for now
1061 continue;
1062 }
1063
Christopher Tate181fafa2009-05-14 11:12:14 -07001064 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001065 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001066 // Find the existing entry with the same package name, and remove it.
1067 // We can't just remove(app) because the instances are different.
1068 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001069 if (entry.packageName.equals(pkg)) {
1070 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001071 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001072 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001073 break;
1074 }
1075 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001076 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001077 mBackupParticipants.delete(uid);
1078 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001079 }
1080 }
1081 }
1082 }
1083
Christopher Tate181fafa2009-05-14 11:12:14 -07001084 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001085 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001086 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001087 int flags = PackageManager.GET_SIGNATURES;
1088 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1089 int N = packages.size();
1090 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001091 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001092 try {
1093 ApplicationInfo app = pkg.applicationInfo;
1094 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001095 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001096 packages.remove(a);
1097 }
1098 else {
1099 // we will need the shared library path, so look that up and store it here
1100 app = mPackageManager.getApplicationInfo(pkg.packageName,
1101 PackageManager.GET_SHARED_LIBRARY_FILES);
1102 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1103 }
1104 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001105 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001106 }
1107 }
Dan Egnorefe52642009-06-24 00:16:33 -07001108 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001109 }
Christopher Tateaa088442009-06-16 18:25:46 -07001110
Christopher Tate3799bc22009-05-06 16:13:56 -07001111 // Reset the given package's known backup participants. Unlike add/remove, the update
1112 // action cannot be passed a null package name.
1113 void updatePackageParticipantsLocked(String packageName) {
1114 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001115 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001116 return;
1117 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001118 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001119
1120 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001121 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001122 List<String> allAppNames = new ArrayList<String>();
1123 for (PackageInfo pkg : allApps) {
1124 allAppNames.add(pkg.packageName);
1125 }
1126 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001127 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001128 }
1129
Christopher Tate84725812010-02-04 15:52:40 -08001130 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001131 // backed up at least once
1132 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001133 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1134
1135 synchronized (mEverStoredApps) {
1136 if (!mEverStoredApps.add(packageName)) return;
1137
1138 RandomAccessFile out = null;
1139 try {
1140 out = new RandomAccessFile(mEverStored, "rws");
1141 out.seek(out.length());
1142 out.writeUTF(packageName);
1143 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001144 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001145 } finally {
1146 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001147 }
1148 }
1149 }
1150
Christopher Tatee97e8072009-07-15 16:45:50 -07001151 // Remove our awareness of having ever backed up the given package
1152 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001154
Dan Egnor852f8e42009-09-30 11:20:45 -07001155 synchronized (mEverStoredApps) {
1156 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1157 // we'll recognize on initialization time that the package no longer
1158 // exists and fix it up then.
1159 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1160 RandomAccessFile known = null;
1161 try {
1162 known = new RandomAccessFile(tempKnownFile, "rws");
1163 mEverStoredApps.remove(packageName);
1164 for (String s : mEverStoredApps) {
1165 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001167 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001168 known.close();
1169 known = null;
1170 if (!tempKnownFile.renameTo(mEverStored)) {
1171 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1172 }
1173 } catch (IOException e) {
1174 // Bad: we couldn't create the new copy. For safety's sake we
1175 // abandon the whole process and remove all what's-backed-up
1176 // state entirely, meaning we'll force a backup pass for every
1177 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001178 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001179 mEverStoredApps.clear();
1180 tempKnownFile.delete();
1181 mEverStored.delete();
1182 } finally {
1183 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001184 }
1185 }
1186 }
1187
Christopher Tateb49ceb32010-02-08 16:22:24 -08001188 // Persistently record the current and ancestral backup tokens as well
1189 // as the set of packages with data [supposedly] available in the
1190 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001191 void writeRestoreTokens() {
1192 try {
1193 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001194
1195 // First, the version number of this record, for futureproofing
1196 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1197
1198 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001199 af.writeLong(mAncestralToken);
1200 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001201
1202 // Now write the set of ancestral packages
1203 if (mAncestralPackages == null) {
1204 af.writeInt(-1);
1205 } else {
1206 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001208 for (String pkgName : mAncestralPackages) {
1209 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001210 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001211 }
1212 }
Christopher Tate84725812010-02-04 15:52:40 -08001213 af.close();
1214 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001215 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001216 }
1217 }
1218
Dan Egnor87a02bc2009-06-17 02:30:10 -07001219 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001220 private IBackupTransport getTransport(String transportName) {
1221 synchronized (mTransports) {
1222 IBackupTransport transport = mTransports.get(transportName);
1223 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001225 }
1226 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001227 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001228 }
1229
Christopher Tatedf01dea2009-06-09 20:45:02 -07001230 // fire off a backup agent, blocking until it attaches or times out
1231 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1232 IBackupAgent agent = null;
1233 synchronized(mAgentConnectLock) {
1234 mConnecting = true;
1235 mConnectedAgent = null;
1236 try {
1237 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001238 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001239
1240 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001241 // only wait 10 seconds for the clear data to happen
1242 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1243 while (mConnecting && mConnectedAgent == null
1244 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001245 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001246 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001247 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001248 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001249 return null;
1250 }
1251 }
1252
1253 // if we timed out with no connect, abort and move on
1254 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001255 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001256 return null;
1257 }
1258 agent = mConnectedAgent;
1259 }
1260 } catch (RemoteException e) {
1261 // can't happen
1262 }
1263 }
1264 return agent;
1265 }
1266
Christopher Tatec7b31e32009-06-10 15:49:30 -07001267 // clear an application's data, blocking until the operation completes or times out
1268 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001269 // Don't wipe packages marked allowClearUserData=false
1270 try {
1271 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1272 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001273 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001274 + packageName);
1275 return;
1276 }
1277 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001278 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001279 return;
1280 }
1281
Christopher Tatec7b31e32009-06-10 15:49:30 -07001282 ClearDataObserver observer = new ClearDataObserver();
1283
1284 synchronized(mClearDataLock) {
1285 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001286 try {
1287 mActivityManager.clearApplicationUserData(packageName, observer);
1288 } catch (RemoteException e) {
1289 // can't happen because the activity manager is in this process
1290 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001291
1292 // only wait 10 seconds for the clear data to happen
1293 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1294 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1295 try {
1296 mClearDataLock.wait(5000);
1297 } catch (InterruptedException e) {
1298 // won't happen, but still.
1299 mClearingData = false;
1300 }
1301 }
1302 }
1303 }
1304
1305 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001306 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001307 synchronized(mClearDataLock) {
1308 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001309 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001310 }
1311 }
1312 }
1313
Christopher Tate1bb69062010-02-19 17:02:12 -08001314 // Get the restore-set token for the best-available restore set for this package:
1315 // the active set if possible, else the ancestral one. Returns zero if none available.
1316 long getAvailableRestoreToken(String packageName) {
1317 long token = mAncestralToken;
1318 synchronized (mQueueLock) {
1319 if (mEverStoredApps.contains(packageName)) {
1320 token = mCurrentToken;
1321 }
1322 }
1323 return token;
1324 }
1325
Christopher Tate44a27902010-01-27 17:15:49 -08001326 // -----
1327 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1328 boolean waitUntilOperationComplete(int token) {
1329 int finalState = OP_PENDING;
1330 synchronized (mCurrentOpLock) {
1331 try {
1332 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1333 try {
1334 mCurrentOpLock.wait();
1335 } catch (InterruptedException e) {}
1336 }
1337 } catch (IndexOutOfBoundsException e) {
1338 // the operation has been mysteriously cleared from our
1339 // bookkeeping -- consider this a success and ignore it.
1340 }
1341 }
1342 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001343 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001344 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001345 return finalState == OP_ACKNOWLEDGED;
1346 }
1347
1348 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001349 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001350 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001351 synchronized (mCurrentOpLock) {
1352 mCurrentOperations.put(token, OP_PENDING);
1353 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1354 mBackupHandler.sendMessageDelayed(msg, interval);
1355 }
Christopher Tate44a27902010-01-27 17:15:49 -08001356 }
1357
Christopher Tate043dadc2009-06-02 16:11:00 -07001358 // ----- Back up a set of applications via a worker thread -----
1359
Christopher Tate44a27902010-01-27 17:15:49 -08001360 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001361 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001362 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001363 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001364 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001365 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001366
Christopher Tate44a27902010-01-27 17:15:49 -08001367 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001368 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001369 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001370 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001371 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001372
1373 try {
1374 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1375 } catch (RemoteException e) {
1376 // can't happen; the transport is local
1377 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 }
1379
Christopher Tate043dadc2009-06-02 16:11:00 -07001380 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001381 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001383 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001384
Christopher Tate79588342009-06-30 16:11:49 -07001385 // Backups run at background priority
1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387
Christopher Tate043dadc2009-06-02 16:11:00 -07001388 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001389 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001390
Dan Egnor852f8e42009-09-30 11:20:45 -07001391 // If we haven't stored package manager metadata yet, we must init the transport.
1392 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1393 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001394 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001395 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001396 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001397 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001398 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001399 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001402 }
Dan Egnor01445162009-09-21 17:04:05 -07001403 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001404
1405 // The package manager doesn't have a proper <application> etc, but since
1406 // it's running here in the system process we can just set up its agent
1407 // directly and use a synthetic BackupRequest. We always run this pass
1408 // because it's cheap and this way we guarantee that we don't get out of
1409 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001410 if (status == BackupConstants.TRANSPORT_OK) {
1411 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1412 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001413 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001414 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1415 status = processOneBackup(pmRequest,
1416 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1417 }
Christopher Tate90967f42009-09-20 15:28:33 -07001418
Dan Egnor01445162009-09-21 17:04:05 -07001419 if (status == BackupConstants.TRANSPORT_OK) {
1420 // Now run all the backups in our queue
1421 status = doQueuedBackups(mTransport);
1422 }
1423
1424 if (status == BackupConstants.TRANSPORT_OK) {
1425 // Tell the transport to finish everything it has buffered
1426 status = mTransport.finishBackup();
1427 if (status == BackupConstants.TRANSPORT_OK) {
1428 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001430 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001431 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001432 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001433 }
1434 }
1435
Dan Egnor01445162009-09-21 17:04:05 -07001436 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001437 // The backend reports that our dataset has been wiped. We need to
1438 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001439 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001440 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001441 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001442 }
1443 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001444 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001445 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001446 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001447 // If everything actually went through and this is the first time we've
1448 // done a backup, we can now record what the current backup dataset token
1449 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001450 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001451 try {
1452 mCurrentToken = mTransport.getCurrentRestoreSet();
1453 } catch (RemoteException e) { /* cannot happen */ }
1454 writeRestoreTokens();
1455 }
1456
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001457 // If things went wrong, we need to re-stage the apps we had expected
1458 // to be backing up in this pass. This journals the package names in
1459 // the current active pending-backup file, not in the we are holding
1460 // here in mJournal.
1461 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001462 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001463 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001464 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001465 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001466
1467 // We also want to reset the backup schedule based on whatever
1468 // the transport suggests by way of retry/backoff time.
1469 try {
1470 startBackupAlarmsLocked(mTransport.requestBackupTime());
1471 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001472 }
1473
1474 // Either backup was successful, in which case we of course do not need
1475 // this pass's journal any more; or it failed, in which case we just
1476 // re-enqueued all of these packages in the current active journal.
1477 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001478 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001480 }
1481
Christopher Tatec2af5d32010-02-02 15:18:58 -08001482 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001483 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001484 backupNow();
1485 }
1486
Dan Egnorbb9001c2009-07-27 12:20:13 -07001487 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001488 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001489 }
1490
Dan Egnor01445162009-09-21 17:04:05 -07001491 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001492 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001493 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001494
Christopher Tatec28083a2010-12-14 16:16:44 -08001495 // Verify that the requested app exists; it might be something that
1496 // requested a backup but was then uninstalled. The request was
1497 // journalled and rather than tamper with the journal it's safer
1498 // to sanity-check here.
1499 try {
1500 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1501 } catch (NameNotFoundException e) {
1502 Slog.d(TAG, "Package does not exist; skipping");
1503 continue;
1504 }
1505
Christopher Tate043dadc2009-06-02 16:11:00 -07001506 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001507 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001508 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001509 agent = bindToAgentSynchronous(request.appInfo,
1510 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001511 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001512 int result = processOneBackup(request, agent, transport);
1513 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001514 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001515 } catch (SecurityException ex) {
1516 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001518 } finally {
1519 try { // unbind even on timeout, just in case
1520 mActivityManager.unbindBackupAgent(request.appInfo);
1521 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001522 }
1523 }
Dan Egnor01445162009-09-21 17:04:05 -07001524
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001525 mWakelock.setWorkSource(null);
1526
Dan Egnor01445162009-09-21 17:04:05 -07001527 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001528 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001529
Dan Egnor01445162009-09-21 17:04:05 -07001530 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1531 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001532 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001533 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001534
Dan Egnorbb9001c2009-07-27 12:20:13 -07001535 File savedStateName = new File(mStateDir, packageName);
1536 File backupDataName = new File(mDataDir, packageName + ".data");
1537 File newStateName = new File(mStateDir, packageName + ".new");
1538
1539 ParcelFileDescriptor savedState = null;
1540 ParcelFileDescriptor backupData = null;
1541 ParcelFileDescriptor newState = null;
1542
1543 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001544 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001545 try {
1546 // Look up the package info & signatures. This is first so that if it
1547 // throws an exception, there's no file setup yet that would need to
1548 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001549 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1550 // The metadata 'package' is synthetic
1551 packInfo = new PackageInfo();
1552 packInfo.packageName = packageName;
1553 } else {
1554 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001556 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001557
Christopher Tatec7b31e32009-06-10 15:49:30 -07001558 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001559 // the saved-state "file". This is by definition an incremental,
1560 // so we build a saved state file to pass.
1561 savedState = ParcelFileDescriptor.open(savedStateName,
1562 ParcelFileDescriptor.MODE_READ_ONLY |
1563 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001564
Dan Egnorbb9001c2009-07-27 12:20:13 -07001565 backupData = ParcelFileDescriptor.open(backupDataName,
1566 ParcelFileDescriptor.MODE_READ_WRITE |
1567 ParcelFileDescriptor.MODE_CREATE |
1568 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001569
Dan Egnorbb9001c2009-07-27 12:20:13 -07001570 newState = ParcelFileDescriptor.open(newStateName,
1571 ParcelFileDescriptor.MODE_READ_WRITE |
1572 ParcelFileDescriptor.MODE_CREATE |
1573 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574
Christopher Tate44a27902010-01-27 17:15:49 -08001575 // Initiate the target's backup pass
1576 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate4a627c72011-04-01 14:43:32 -07001577 agent.doBackup(savedState, backupData, newState, false,
1578 token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001579 boolean success = waitUntilOperationComplete(token);
1580
1581 if (!success) {
1582 // timeout -- bail out into the failed-transaction logic
1583 throw new RuntimeException("Backup timeout");
1584 }
1585
Dan Egnorbb9001c2009-07-27 12:20:13 -07001586 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001588 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001590 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001591 backupDataName.delete();
1592 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001593 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001594 } finally {
1595 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1596 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1597 try { if (newState != null) newState.close(); } catch (IOException e) {}
1598 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001599 synchronized (mCurrentOpLock) {
1600 mCurrentOperations.clear();
1601 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001602 }
1603
1604 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001605 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 try {
1607 int size = (int) backupDataName.length();
1608 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001609 if (result == BackupConstants.TRANSPORT_OK) {
1610 backupData = ParcelFileDescriptor.open(backupDataName,
1611 ParcelFileDescriptor.MODE_READ_ONLY);
1612 result = transport.performBackup(packInfo, backupData);
1613 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614
Dan Egnor83861e72009-09-17 16:17:55 -07001615 // TODO - We call finishBackup() for each application backed up, because
1616 // we need to know now whether it succeeded or failed. Instead, we should
1617 // hold off on finishBackup() until the end, which implies holding off on
1618 // renaming *all* the output state files (see below) until that happens.
1619
Dan Egnor01445162009-09-21 17:04:05 -07001620 if (result == BackupConstants.TRANSPORT_OK) {
1621 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001622 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 }
1626
1627 // After successful transport, delete the now-stale data
1628 // and juggle the files so that next time we supply the agent
1629 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001630 if (result == BackupConstants.TRANSPORT_OK) {
1631 backupDataName.delete();
1632 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001634 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001635 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001636 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001637 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001639 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001640 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001641 } finally {
1642 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001643 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001644
Dan Egnor01445162009-09-21 17:04:05 -07001645 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001646 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001647 }
1648
Christopher Tatedf01dea2009-06-09 20:45:02 -07001649
Christopher Tate4a627c72011-04-01 14:43:32 -07001650 // ----- Full backup to a file/socket -----
1651
1652 class PerformFullBackupTask implements Runnable {
1653 ParcelFileDescriptor mOutputFile;
1654 IFullBackupRestoreObserver mObserver;
1655 boolean mIncludeApks;
1656 boolean mIncludeShared;
1657 boolean mAllApps;
1658 String[] mPackages;
1659 AtomicBoolean mLatchObject;
1660 File mFilesDir;
1661 File mManifestFile;
1662
1663 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1664 boolean includeApks, boolean includeShared,
1665 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1666 mOutputFile = fd;
1667 mObserver = observer;
1668 mIncludeApks = includeApks;
1669 mIncludeShared = includeShared;
1670 mAllApps = doAllApps;
1671 mPackages = packages;
1672 mLatchObject = latch;
1673
1674 mFilesDir = new File("/data/system");
1675 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1676 }
1677
1678 @Override
1679 public void run() {
1680 final List<PackageInfo> packagesToBackup;
1681
1682 sendStartBackup();
1683
1684 // doAllApps supersedes the package set if any
1685 if (mAllApps) {
1686 packagesToBackup = mPackageManager.getInstalledPackages(
1687 PackageManager.GET_SIGNATURES);
1688 } else {
1689 packagesToBackup = new ArrayList<PackageInfo>();
1690 for (String pkgName : mPackages) {
1691 try {
1692 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1693 PackageManager.GET_SIGNATURES));
1694 } catch (NameNotFoundException e) {
1695 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1696 }
1697 }
1698 }
1699
1700 // Now back up the app data via the agent mechanism
1701 PackageInfo pkg = null;
1702 try {
1703 int N = packagesToBackup.size();
1704 for (int i = 0; i < N; i++) {
1705 pkg = packagesToBackup.get(i);
1706
1707 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1708
1709 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1710 IApplicationThread.BACKUP_MODE_FULL);
1711 if (agent != null) {
1712 try {
1713 ApplicationInfo app = mPackageManager.getApplicationInfo(
1714 pkg.packageName, 0);
1715 boolean sendApk = mIncludeApks
1716 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1717 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1718 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1719
1720 sendOnBackupPackage(pkg.packageName);
1721
1722 {
1723 BackupDataOutput output = new BackupDataOutput(
1724 mOutputFile.getFileDescriptor());
1725
1726 if (DEBUG) Slog.d(TAG, "Writing manifest for " + pkg.packageName);
1727 writeAppManifest(pkg, mManifestFile, sendApk);
1728 FullBackup.backupToTar(pkg.packageName, null, null,
1729 mFilesDir.getAbsolutePath(),
1730 mManifestFile.getAbsolutePath(),
1731 output);
1732 }
1733
1734 if (DEBUG) Slog.d(TAG, "Calling doBackup()");
1735 final int token = generateToken();
1736 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL);
1737 agent.doBackup(null, mOutputFile, null, sendApk,
1738 token, mBackupManagerBinder);
1739 boolean success = waitUntilOperationComplete(token);
1740 if (!success) {
1741 Slog.d(TAG, "Full backup failed on package " + pkg.packageName);
1742 } else {
1743 if (DEBUG) Slog.d(TAG, "Full backup success: " + pkg.packageName);
1744 }
1745 } catch (NameNotFoundException e) {
1746 Slog.e(TAG, "Package exists but not app info; skipping: "
1747 + pkg.packageName);
1748 } catch (IOException e) {
1749 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
1750 }
1751 } else {
1752 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1753 }
1754 tearDown(pkg);
1755 }
1756 } catch (RemoteException e) {
1757 Slog.e(TAG, "App died during full backup");
1758 } finally {
1759 if (pkg != null) {
1760 tearDown(pkg);
1761 }
1762 try {
1763 mOutputFile.close();
1764 } catch (IOException e) {
1765 /* nothing we can do about this */
1766 }
1767 synchronized (mCurrentOpLock) {
1768 mCurrentOperations.clear();
1769 }
1770 synchronized (mLatchObject) {
1771 mLatchObject.set(true);
1772 mLatchObject.notifyAll();
1773 }
1774 sendEndBackup();
1775 mWakelock.release();
1776 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1777 }
1778 }
1779
1780 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1781 throws IOException {
1782 // Manifest format. All data are strings ending in LF:
1783 // BACKUP_MANIFEST_VERSION, currently 1
1784 //
1785 // Version 1:
1786 // package name
1787 // package's versionCode
1788 // boolean: "1" if archive includes .apk, "0" otherwise
1789 // number of signatures == N
1790 // N*: signature byte array in ascii format per Signature.toCharsString()
1791 StringBuilder builder = new StringBuilder(4096);
1792 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
1793
1794 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
1795 printer.println(pkg.packageName);
1796 printer.println(Integer.toString(pkg.versionCode));
1797 printer.println(withApk ? "1" : "0");
1798 if (pkg.signatures == null) {
1799 printer.println("0");
1800 } else {
1801 printer.println(Integer.toString(pkg.signatures.length));
1802 for (Signature sig : pkg.signatures) {
1803 printer.println(sig.toCharsString());
1804 }
1805 }
1806
1807 FileOutputStream outstream = new FileOutputStream(manifestFile);
1808 Libcore.os.ftruncate(outstream.getFD(), 0);
1809 outstream.write(builder.toString().getBytes());
1810 outstream.close();
1811 }
1812
1813 private void tearDown(PackageInfo pkg) {
1814 final ApplicationInfo app = pkg.applicationInfo;
1815 try {
1816 // unbind and tidy up even on timeout or failure, just in case
1817 mActivityManager.unbindBackupAgent(app);
1818
1819 // The agent was running with a stub Application object, so shut it down
1820 if (app.uid != Process.SYSTEM_UID) {
1821 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
1822 mActivityManager.killApplicationProcess(app.processName, app.uid);
1823 } else {
1824 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
1825 }
1826 } catch (RemoteException e) {
1827 Slog.d(TAG, "Lost app trying to shut down");
1828 }
1829 }
1830
1831 // wrappers for observer use
1832 void sendStartBackup() {
1833 if (mObserver != null) {
1834 try {
1835 mObserver.onStartBackup();
1836 } catch (RemoteException e) {
1837 Slog.w(TAG, "full backup observer went away: startBackup");
1838 mObserver = null;
1839 }
1840 }
1841 }
1842
1843 void sendOnBackupPackage(String name) {
1844 if (mObserver != null) {
1845 try {
1846 // TODO: use a more user-friendly name string
1847 mObserver.onBackupPackage(name);
1848 } catch (RemoteException e) {
1849 Slog.w(TAG, "full backup observer went away: backupPackage");
1850 mObserver = null;
1851 }
1852 }
1853 }
1854
1855 void sendEndBackup() {
1856 if (mObserver != null) {
1857 try {
1858 mObserver.onEndBackup();
1859 } catch (RemoteException e) {
1860 Slog.w(TAG, "full backup observer went away: endBackup");
1861 mObserver = null;
1862 }
1863 }
1864 }
1865 }
1866
1867
Christopher Tatedf01dea2009-06-09 20:45:02 -07001868 // ----- Restore handling -----
1869
Christopher Tate78dd4a72009-11-04 11:49:08 -08001870 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1871 // If the target resides on the system partition, we allow it to restore
1872 // data from the like-named package in a restore set even if the signatures
1873 // do not match. (Unlike general applications, those flashed to the system
1874 // partition will be signed with the device's platform certificate, so on
1875 // different phones the same system app will have different signatures.)
1876 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001877 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001878 return true;
1879 }
1880
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001881 // Allow unsigned apps, but not signed on one device and unsigned on the other
1882 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001883 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001884 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001885 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001886 if ((storedSigs == null || storedSigs.length == 0)
1887 && (deviceSigs == null || deviceSigs.length == 0)) {
1888 return true;
1889 }
1890 if (storedSigs == null || deviceSigs == null) {
1891 return false;
1892 }
1893
Christopher Tateabce4e82009-06-18 18:35:32 -07001894 // !!! TODO: this demands that every stored signature match one
1895 // that is present on device, and does not demand the converse.
1896 // Is this this right policy?
1897 int nStored = storedSigs.length;
1898 int nDevice = deviceSigs.length;
1899
1900 for (int i=0; i < nStored; i++) {
1901 boolean match = false;
1902 for (int j=0; j < nDevice; j++) {
1903 if (storedSigs[i].equals(deviceSigs[j])) {
1904 match = true;
1905 break;
1906 }
1907 }
1908 if (!match) {
1909 return false;
1910 }
1911 }
1912 return true;
1913 }
1914
Christopher Tate44a27902010-01-27 17:15:49 -08001915 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001916 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001917 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001918 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001919 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001920 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001921 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001922 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001923
Christopher Tate5cbbf562009-06-22 16:44:51 -07001924 class RestoreRequest {
1925 public PackageInfo app;
1926 public int storedAppVersion;
1927
1928 RestoreRequest(PackageInfo _app, int _version) {
1929 app = _app;
1930 storedAppVersion = _version;
1931 }
1932 }
1933
Christopher Tate44a27902010-01-27 17:15:49 -08001934 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001935 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1936 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001937 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001938 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001939 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001940 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001941 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001942 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001943
1944 try {
1945 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1946 } catch (RemoteException e) {
1947 // can't happen; the transport is local
1948 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001949 }
1950
Christopher Tatedf01dea2009-06-09 20:45:02 -07001951 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001952 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001953 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001954 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001955 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001956
Christopher Tateb49ceb32010-02-08 16:22:24 -08001957 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001958 int error = -1; // assume error
1959
Dan Egnorefe52642009-06-24 00:16:33 -07001960 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001961 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001962 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001963 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001964
Dan Egnorefe52642009-06-24 00:16:33 -07001965 // Get the list of all packages which have backup enabled.
1966 // (Include the Package Manager metadata pseudo-package first.)
1967 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1968 PackageInfo omPackage = new PackageInfo();
1969 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1970 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001971
Dan Egnorefe52642009-06-24 00:16:33 -07001972 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001973 if (mTargetPackage == null) {
1974 restorePackages.addAll(agentPackages);
1975 } else {
1976 // Just one package to attempt restore of
1977 restorePackages.add(mTargetPackage);
1978 }
Dan Egnorefe52642009-06-24 00:16:33 -07001979
Christopher Tate7d562ec2009-06-25 18:03:43 -07001980 // let the observer know that we're running
1981 if (mObserver != null) {
1982 try {
1983 // !!! TODO: get an actual count from the transport after
1984 // its startRestore() runs?
1985 mObserver.restoreStarting(restorePackages.size());
1986 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001987 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001988 mObserver = null;
1989 }
1990 }
1991
Dan Egnor01445162009-09-21 17:04:05 -07001992 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1993 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001994 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001995 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001996 return;
1997 }
1998
1999 String packageName = mTransport.nextRestorePackage();
2000 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002001 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002002 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07002003 return;
2004 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002005 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002006 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002007 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07002008 return;
2009 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002010 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07002011 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002012 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002013 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002014 return;
2015 }
2016
2017 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08002018 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07002019 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07002020 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
2021 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07002022
Christopher Tate8c032472009-07-02 14:28:47 -07002023 // Verify that the backup set includes metadata. If not, we can't do
2024 // signature/version verification etc, so we simply do not proceed with
2025 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07002026 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002027 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002028 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002029 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07002030 return;
2031 }
2032
Christopher Tate7d562ec2009-06-25 18:03:43 -07002033 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07002034 for (;;) {
2035 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002036
Dan Egnorefe52642009-06-24 00:16:33 -07002037 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002038 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002039 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07002040 return;
2041 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002042 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07002043 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002044 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002045
Christopher Tate7d562ec2009-06-25 18:03:43 -07002046 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07002047 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07002048 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07002049 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002050 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002051 mObserver = null;
2052 }
2053 }
2054
Dan Egnorefe52642009-06-24 00:16:33 -07002055 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
2056 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002058 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002059 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002060 continue;
2061 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002062
Dan Egnorbb9001c2009-07-27 12:20:13 -07002063 PackageInfo packageInfo;
2064 try {
2065 int flags = PackageManager.GET_SIGNATURES;
2066 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
2067 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002068 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002069 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002070 "Package missing on device");
2071 continue;
2072 }
2073
Dan Egnorefe52642009-06-24 00:16:33 -07002074 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08002075 // Data is from a "newer" version of the app than we have currently
2076 // installed. If the app has not declared that it is prepared to
2077 // handle this case, we do not attempt the restore.
2078 if ((packageInfo.applicationInfo.flags
2079 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
2080 String message = "Version " + metaInfo.versionCode
2081 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002082 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08002083 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
2084 packageName, message);
2085 continue;
2086 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002087 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08002088 + " > installed " + packageInfo.versionCode
2089 + " but restoreAnyVersion");
2090 }
Dan Egnorefe52642009-06-24 00:16:33 -07002091 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002092
Christopher Tate78dd4a72009-11-04 11:49:08 -08002093 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002094 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002095 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002096 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07002097 continue;
2098 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002099
Joe Onorato8a9b2202010-02-26 18:56:32 -08002100 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07002101 + " restore version [" + metaInfo.versionCode
2102 + "] is compatible with installed version ["
2103 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07002104
Christopher Tate3de55bc2010-03-12 17:28:08 -08002105 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07002106 IBackupAgent agent = bindToAgentSynchronous(
2107 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08002108 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07002109 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002110 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002111 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002112 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002113 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002114 }
2115
Christopher Tate5e1ab332009-09-01 20:32:49 -07002116 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07002117 try {
Chris Tate249345b2010-10-29 12:57:04 -07002118 processOneRestore(packageInfo, metaInfo.versionCode, agent,
2119 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002120 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07002121 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07002122 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07002123 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07002124
2125 // The agent was probably running with a stub Application object,
2126 // which isn't a valid run mode for the main app logic. Shut
2127 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08002128 // usual full initialization. Note that this is only done for
2129 // full-system restores: when a single app has requested a restore,
2130 // it is explicitly not killed following that operation.
2131 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07002132 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002133 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07002134 + packageInfo.applicationInfo.processName);
2135 mActivityManager.killApplicationProcess(
2136 packageInfo.applicationInfo.processName,
2137 packageInfo.applicationInfo.uid);
2138 }
Dan Egnorefe52642009-06-24 00:16:33 -07002139 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002140 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002141
2142 // if we get this far, report success to the observer
2143 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002144 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002145 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002146 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002147 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002148 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002149 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002150
Dan Egnorefe52642009-06-24 00:16:33 -07002151 try {
2152 mTransport.finishRestore();
2153 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002154 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002155 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002156
2157 if (mObserver != null) {
2158 try {
2159 mObserver.restoreFinished(error);
2160 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002161 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002162 }
2163 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002164
Christopher Tate84725812010-02-04 15:52:40 -08002165 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08002166 // ancestral dataset, as well as the set of apps that are possibly
2167 // restoreable from the dataset
2168 if (mTargetPackage == null && pmAgent != null) {
2169 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08002170 mAncestralToken = mToken;
2171 writeRestoreTokens();
2172 }
2173
Christopher Tate1bb69062010-02-19 17:02:12 -08002174 // We must under all circumstances tell the Package Manager to
2175 // proceed with install notifications if it's waiting for us.
2176 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002177 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08002178 try {
2179 mPackageManagerBinder.finishPackageInstall(mPmToken);
2180 } catch (RemoteException e) { /* can't happen */ }
2181 }
2182
Christopher Tate73a3cb32010-12-13 18:27:26 -08002183 // Furthermore we need to reset the session timeout clock
2184 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2185 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
2186 TIMEOUT_RESTORE_INTERVAL);
2187
Christopher Tateb6787f22009-07-02 17:40:45 -07002188 // done; we can finally release the wakelock
2189 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07002190 }
2191 }
2192
Dan Egnorefe52642009-06-24 00:16:33 -07002193 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07002194 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
2195 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07002196 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07002197 final String packageName = app.packageName;
2198
Joe Onorato8a9b2202010-02-26 18:56:32 -08002199 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002200
Christopher Tatec7b31e32009-06-10 15:49:30 -07002201 // !!! TODO: get the dirs from the transport
2202 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002203 File newStateName = new File(mStateDir, packageName + ".new");
2204 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002205
Dan Egnorbb9001c2009-07-27 12:20:13 -07002206 ParcelFileDescriptor backupData = null;
2207 ParcelFileDescriptor newState = null;
2208
Christopher Tate4a627c72011-04-01 14:43:32 -07002209 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002210 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07002211 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07002212 backupData = ParcelFileDescriptor.open(backupDataName,
2213 ParcelFileDescriptor.MODE_READ_WRITE |
2214 ParcelFileDescriptor.MODE_CREATE |
2215 ParcelFileDescriptor.MODE_TRUNCATE);
2216
Dan Egnor01445162009-09-21 17:04:05 -07002217 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002218 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002219 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002220 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07002221 }
2222
2223 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07002224 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002225 backupData = ParcelFileDescriptor.open(backupDataName,
2226 ParcelFileDescriptor.MODE_READ_ONLY);
2227
Dan Egnorbb9001c2009-07-27 12:20:13 -07002228 newState = ParcelFileDescriptor.open(newStateName,
2229 ParcelFileDescriptor.MODE_READ_WRITE |
2230 ParcelFileDescriptor.MODE_CREATE |
2231 ParcelFileDescriptor.MODE_TRUNCATE);
2232
Christopher Tate44a27902010-01-27 17:15:49 -08002233 // Kick off the restore, checking for hung agents
2234 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
2235 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
2236 boolean success = waitUntilOperationComplete(token);
2237
2238 if (!success) {
2239 throw new RuntimeException("restore timeout");
2240 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002241
2242 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07002243 //
2244 // !!! TODO: the restored data should be migrated on the server
2245 // side into the current dataset. In that case the new state file
2246 // we just created would reflect the data already extant in the
2247 // backend, so there'd be nothing more to do. Until that happens,
2248 // however, we need to make sure that we record the data to the
2249 // current backend dataset. (Yes, this means shipping the data over
2250 // the wire in both directions. That's bad, but consistency comes
2251 // first, then efficiency.) Once we introduce server-side data
2252 // migration to the newly-restored device's dataset, we will change
2253 // the following from a discard of the newly-written state to the
2254 // "correct" operation of renaming into the canonical state blob.
2255 newStateName.delete(); // TODO: remove; see above comment
2256 //newStateName.renameTo(savedStateName); // TODO: replace with this
2257
Dan Egnorbb9001c2009-07-27 12:20:13 -07002258 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002259 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002260 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002261 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07002263
Christopher Tate96733042009-07-20 14:49:13 -07002264 // If the agent fails restore, it might have put the app's data
2265 // into an incoherent state. For consistency we wipe its data
2266 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07002267 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07002268 } finally {
2269 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002270 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2271 try { if (newState != null) newState.close(); } catch (IOException e) {}
2272 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07002273 synchronized (mCurrentOperations) {
2274 mCurrentOperations.delete(token);
2275 }
Chris Tate249345b2010-10-29 12:57:04 -07002276
2277 // If we know a priori that we'll need to perform a full post-restore backup
2278 // pass, clear the new state file data. This means we're discarding work that
2279 // was just done by the app's agent, but this way the agent doesn't need to
2280 // take any special action based on global device state.
2281 if (needFullBackup) {
2282 newStateName.delete();
2283 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002284 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002285 }
2286 }
2287
Christopher Tate44a27902010-01-27 17:15:49 -08002288 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002289 IBackupTransport mTransport;
2290 PackageInfo mPackage;
2291
Christopher Tate44a27902010-01-27 17:15:49 -08002292 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002293 mTransport = transport;
2294 mPackage = packageInfo;
2295 }
2296
Christopher Tateee0e78a2009-07-02 11:17:03 -07002297 public void run() {
2298 try {
2299 // Clear the on-device backup state to ensure a full backup next time
2300 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
2301 File stateFile = new File(stateDir, mPackage.packageName);
2302 stateFile.delete();
2303
2304 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07002305 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002306 mTransport.clearBackupData(mPackage);
2307 } catch (RemoteException e) {
2308 // can't happen; the transport is local
2309 } finally {
2310 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07002311 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002312 mTransport.finishBackup();
2313 } catch (RemoteException e) {
2314 // can't happen; the transport is local
2315 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002316
2317 // Last but not least, release the cpu
2318 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002319 }
2320 }
2321 }
2322
Christopher Tate44a27902010-01-27 17:15:49 -08002323 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002324 HashSet<String> mQueue;
2325
Christopher Tate44a27902010-01-27 17:15:49 -08002326 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002327 mQueue = transportNames;
2328 }
2329
Christopher Tate4cc86e12009-09-21 19:36:51 -07002330 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002331 try {
2332 for (String transportName : mQueue) {
2333 IBackupTransport transport = getTransport(transportName);
2334 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002335 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002336 continue;
2337 }
2338
Joe Onorato8a9b2202010-02-26 18:56:32 -08002339 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002340 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002341 long startRealtime = SystemClock.elapsedRealtime();
2342 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002343
Christopher Tate4cc86e12009-09-21 19:36:51 -07002344 if (status == BackupConstants.TRANSPORT_OK) {
2345 status = transport.finishBackup();
2346 }
2347
2348 // Okay, the wipe really happened. Clean up our local bookkeeping.
2349 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002350 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002351 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002352 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002353 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002354 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002355 synchronized (mQueueLock) {
2356 recordInitPendingLocked(false, transportName);
2357 }
Dan Egnor726247c2009-09-29 19:12:31 -07002358 } else {
2359 // If this didn't work, requeue this one and try again
2360 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002361 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002362 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002363 synchronized (mQueueLock) {
2364 recordInitPendingLocked(true, transportName);
2365 }
2366 // do this via another alarm to make sure of the wakelock states
2367 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002368 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002369 + transportName + " resched in " + delay);
2370 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2371 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002372 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002373 }
2374 } catch (RemoteException e) {
2375 // can't happen; the transports are local
2376 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002377 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002378 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002379 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002380 mWakelock.release();
2381 }
2382 }
2383 }
2384
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002385 private void dataChangedImpl(String packageName) {
2386 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2387 dataChangedImpl(packageName, targets);
2388 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002389
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002390 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002391 // Record that we need a backup pass for the caller. Since multiple callers
2392 // may share a uid, we need to note all candidates within that uid and schedule
2393 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002394 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002395
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002396 if (targets == null) {
2397 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2398 + " uid=" + Binder.getCallingUid());
2399 return;
2400 }
2401
2402 synchronized (mQueueLock) {
2403 // Note that this client has made data changes that need to be backed up
2404 for (ApplicationInfo app : targets) {
2405 // validate the caller-supplied package name against the known set of
2406 // packages associated with this uid
2407 if (app.packageName.equals(packageName)) {
2408 // Add the caller to the set of pending backups. If there is
2409 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07002410 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08002411 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002412 // Journal this request in case of crash. The put()
2413 // operation returned null when this package was not already
2414 // in the set; we want to avoid touching the disk redundantly.
2415 writeToJournalLocked(packageName);
2416
2417 if (DEBUG) {
2418 int numKeys = mPendingBackups.size();
2419 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2420 for (BackupRequest b : mPendingBackups.values()) {
2421 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2422 }
2423 }
2424 }
2425 }
2426 }
2427 }
2428 }
2429
2430 // Note: packageName is currently unused, but may be in the future
2431 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002432 // If the caller does not hold the BACKUP permission, it can only request a
2433 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002434 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002435 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002436 synchronized (mBackupParticipants) {
2437 return mBackupParticipants.get(Binder.getCallingUid());
2438 }
2439 }
2440
2441 // a caller with full permission can ask to back up any participating app
2442 // !!! TODO: allow backup of ANY app?
2443 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2444 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002445 int N = mBackupParticipants.size();
2446 for (int i = 0; i < N; i++) {
2447 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2448 if (s != null) {
2449 targets.addAll(s);
2450 }
2451 }
2452 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002453 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002454 }
Christopher Tate46758122009-05-06 11:22:00 -07002455
Christopher Tatecde87f42009-06-12 12:55:53 -07002456 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002457 RandomAccessFile out = null;
2458 try {
2459 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2460 out = new RandomAccessFile(mJournal, "rws");
2461 out.seek(out.length());
2462 out.writeUTF(str);
2463 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002464 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002465 mJournal = null;
2466 } finally {
2467 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002468 }
2469 }
2470
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002471 // ----- IBackupManager binder interface -----
2472
2473 public void dataChanged(final String packageName) {
2474 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2475 if (targets == null) {
2476 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2477 + " uid=" + Binder.getCallingUid());
2478 return;
2479 }
2480
2481 mBackupHandler.post(new Runnable() {
2482 public void run() {
2483 dataChangedImpl(packageName, targets);
2484 }
2485 });
2486 }
2487
Christopher Tateee0e78a2009-07-02 11:17:03 -07002488 // Clear the given package's backup data from the current transport
2489 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002490 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002491 PackageInfo info;
2492 try {
2493 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2494 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002495 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002496 return;
2497 }
2498
2499 // If the caller does not hold the BACKUP permission, it can only request a
2500 // wipe of its own backed-up data.
2501 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002502 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002503 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2504 apps = mBackupParticipants.get(Binder.getCallingUid());
2505 } else {
2506 // a caller with full permission can ask to back up any participating app
2507 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002508 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002509 apps = new HashSet<ApplicationInfo>();
2510 int N = mBackupParticipants.size();
2511 for (int i = 0; i < N; i++) {
2512 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2513 if (s != null) {
2514 apps.addAll(s);
2515 }
2516 }
2517 }
2518
2519 // now find the given package in the set of candidate apps
2520 for (ApplicationInfo app : apps) {
2521 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002522 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002523 // found it; fire off the clear request
2524 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002525 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002526 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002527 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2528 new ClearParams(getTransport(mCurrentTransport), info));
2529 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002530 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002531 }
2532 break;
2533 }
2534 }
2535 }
2536
Christopher Tateace7f092009-06-15 18:07:25 -07002537 // Run a backup pass immediately for any applications that have declared
2538 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002539 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002541
Joe Onorato8a9b2202010-02-26 18:56:32 -08002542 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002543 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002544 // Because the alarms we are using can jitter, and we want an *immediate*
2545 // backup pass to happen, we restart the timer beginning with "next time,"
2546 // then manually fire the backup trigger intent ourselves.
2547 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002548 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002549 mRunBackupIntent.send();
2550 } catch (PendingIntent.CanceledException e) {
2551 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002552 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002553 }
Christopher Tate46758122009-05-06 11:22:00 -07002554 }
2555 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002556
Christopher Tate4a627c72011-04-01 14:43:32 -07002557 // Run a *full* backup pass for the given package, writing the resulting data stream
2558 // to the supplied file descriptor. This method is synchronous and does not return
2559 // to the caller until the backup has been completed.
2560 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
2561 boolean doAllApps, String[] pkgList) {
2562 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2563
2564 // Validate
2565 if (!doAllApps) {
2566 if (!includeShared) {
2567 // If we're backing up shared data (sdcard or equivalent), then we can run
2568 // without any supplied app names. Otherwise, we'd be doing no work, so
2569 // report the error.
2570 if (pkgList == null || pkgList.length == 0) {
2571 throw new IllegalArgumentException(
2572 "Backup requested but neither shared nor any apps named");
2573 }
2574 }
2575 }
2576
2577 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
2578 + " shared=" + includeShared + " all=" + doAllApps
2579 + " pkgs=" + pkgList);
2580
2581 long oldId = Binder.clearCallingIdentity();
2582 try {
2583 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
2584 doAllApps, pkgList);
2585 final int token = generateToken();
2586 synchronized (mFullConfirmations) {
2587 mFullConfirmations.put(token, params);
2588 }
2589
2590 // start up the confirmation UI, making sure the screen lights up
2591 if (DEBUG) Slog.d(TAG, "Starting confirmation UI, token=" + token);
2592 try {
2593 Intent confIntent = new Intent(FullBackup.FULL_BACKUP_INTENT_ACTION);
2594 confIntent.setClassName("com.android.backupconfirm",
2595 "com.android.backupconfirm.BackupRestoreConfirmation");
2596 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
2597 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2598 mContext.startActivity(confIntent);
2599 } catch (ActivityNotFoundException e) {
2600 Slog.e(TAG, "Unable to launch full backup confirmation", e);
2601 mFullConfirmations.delete(token);
2602 return;
2603 }
2604 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
2605
2606 // start the confirmation countdown
2607 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
2608 + TIMEOUT_FULL_CONFIRMATION + " millis");
2609 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
2610 token, 0, params);
2611 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
2612
2613 // wait for the backup to be performed
2614 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
2615 waitForCompletion(params);
2616 if (DEBUG) Slog.d(TAG, "...Full backup operation complete!");
2617 } finally {
2618 Binder.restoreCallingIdentity(oldId);
2619 try {
2620 fd.close();
2621 } catch (IOException e) {
2622 // just eat it
2623 }
2624 }
2625 }
2626
2627 void waitForCompletion(FullParams params) {
2628 synchronized (params.latch) {
2629 while (params.latch.get() == false) {
2630 try {
2631 params.latch.wait();
2632 } catch (InterruptedException e) { /* never interrupted */ }
2633 }
2634 }
2635 }
2636
2637 void signalFullBackupRestoreCompletion(FullParams params) {
2638 synchronized (params.latch) {
2639 params.latch.set(true);
2640 params.latch.notifyAll();
2641 }
2642 }
2643
2644 // Confirm that the previously-requested full backup/restore operation can proceed. This
2645 // is used to require a user-facing disclosure about the operation.
2646 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
2647 IFullBackupRestoreObserver observer) {
2648 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
2649 + " allow=" + allow);
2650
2651 // TODO: possibly require not just this signature-only permission, but even
2652 // require that the specific designated confirmation-UI app uid is the caller?
2653 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2654
2655 long oldId = Binder.clearCallingIdentity();
2656 try {
2657
2658 FullParams params;
2659 synchronized (mFullConfirmations) {
2660 params = mFullConfirmations.get(token);
2661 if (params != null) {
2662 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
2663 mFullConfirmations.delete(token);
2664
2665 if (allow) {
2666 params.observer = observer;
2667 final int verb = params instanceof FullBackupParams
2668 ? MSG_RUN_FULL_BACKUP
2669 : MSG_RUN_FULL_RESTORE;
2670
2671 mWakelock.acquire();
2672 Message msg = mBackupHandler.obtainMessage(verb, params);
2673 mBackupHandler.sendMessage(msg);
2674 } else {
2675 Slog.w(TAG, "User rejected full backup/restore operation");
2676 // indicate completion without having actually transferred any data
2677 signalFullBackupRestoreCompletion(params);
2678 }
2679 } else {
2680 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
2681 }
2682 }
2683 } finally {
2684 Binder.restoreCallingIdentity(oldId);
2685 }
2686 }
2687
Christopher Tate8031a3d2009-07-06 16:36:05 -07002688 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002689 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002690 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07002691 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002692
Joe Onorato8a9b2202010-02-26 18:56:32 -08002693 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002694
Christopher Tate6ef58a12009-06-29 14:56:28 -07002695 boolean wasEnabled = mEnabled;
2696 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002697 Settings.Secure.putInt(mContext.getContentResolver(),
2698 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002699 mEnabled = enable;
2700 }
2701
Christopher Tate49401dd2009-07-01 12:34:29 -07002702 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002703 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002704 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002705 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002706 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002707 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002708 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002709
Christopher Tateb6787f22009-07-02 17:40:45 -07002710 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002711
2712 // This also constitutes an opt-out, so we wipe any data for
2713 // this device from the backend. We start that process with
2714 // an alarm in order to guarantee wakelock states.
2715 if (wasEnabled && mProvisioned) {
2716 // NOTE: we currently flush every registered transport, not just
2717 // the currently-active one.
2718 HashSet<String> allTransports;
2719 synchronized (mTransports) {
2720 allTransports = new HashSet<String>(mTransports.keySet());
2721 }
2722 // build the set of transports for which we are posting an init
2723 for (String transport : allTransports) {
2724 recordInitPendingLocked(true, transport);
2725 }
2726 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2727 mRunInitIntent);
2728 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002729 }
2730 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002731 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002732
Christopher Tatecce9da52010-02-03 15:11:15 -08002733 // Enable/disable automatic restore of app data at install time
2734 public void setAutoRestore(boolean doAutoRestore) {
2735 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2736 "setBackupEnabled");
2737
Joe Onorato8a9b2202010-02-26 18:56:32 -08002738 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002739
2740 synchronized (this) {
2741 Settings.Secure.putInt(mContext.getContentResolver(),
2742 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2743 mAutoRestore = doAutoRestore;
2744 }
2745 }
2746
Christopher Tate8031a3d2009-07-06 16:36:05 -07002747 // Mark the backup service as having been provisioned
2748 public void setBackupProvisioned(boolean available) {
2749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2750 "setBackupProvisioned");
2751
2752 boolean wasProvisioned = mProvisioned;
2753 synchronized (this) {
2754 Settings.Secure.putInt(mContext.getContentResolver(),
2755 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2756 mProvisioned = available;
2757 }
2758
2759 synchronized (mQueueLock) {
2760 if (available && !wasProvisioned && mEnabled) {
2761 // we're now good to go, so start the backup alarms
2762 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2763 } else if (!available) {
2764 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002765 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002766 mAlarmManager.cancel(mRunBackupIntent);
2767 }
2768 }
2769 }
2770
2771 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002772 // We used to use setInexactRepeating(), but that may be linked to
2773 // backups running at :00 more often than not, creating load spikes.
2774 // Schedule at an exact time for now, and also add a bit of "fuzz".
2775
2776 Random random = new Random();
2777 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2778 random.nextInt(FUZZ_MILLIS);
2779 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2780 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002781 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002782 }
2783
Christopher Tate6ef58a12009-06-29 14:56:28 -07002784 // Report whether the backup mechanism is currently enabled
2785 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002787 return mEnabled; // no need to synchronize just to read it
2788 }
2789
Christopher Tate91717492009-06-26 21:07:13 -07002790 // Report the name of the currently active transport
2791 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002793 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002794 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002795 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002796 }
2797
Christopher Tate91717492009-06-26 21:07:13 -07002798 // Report all known, available backup transports
2799 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002801
Christopher Tate91717492009-06-26 21:07:13 -07002802 String[] list = null;
2803 ArrayList<String> known = new ArrayList<String>();
2804 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2805 if (entry.getValue() != null) {
2806 known.add(entry.getKey());
2807 }
2808 }
2809
2810 if (known.size() > 0) {
2811 list = new String[known.size()];
2812 known.toArray(list);
2813 }
2814 return list;
2815 }
2816
2817 // Select which transport to use for the next backup operation. If the given
2818 // name is not one of the available transports, no action is taken and the method
2819 // returns null.
2820 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002821 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002822
2823 synchronized (mTransports) {
2824 String prevTransport = null;
2825 if (mTransports.get(transport) != null) {
2826 prevTransport = mCurrentTransport;
2827 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002828 Settings.Secure.putString(mContext.getContentResolver(),
2829 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002830 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002831 + " returning " + prevTransport);
2832 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002833 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002834 }
2835 return prevTransport;
2836 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002837 }
2838
Christopher Tatef5e1c292010-12-08 18:40:26 -08002839 // Supply the configuration Intent for the given transport. If the name is not one
2840 // of the available transports, or if the transport does not supply any configuration
2841 // UI, the method returns null.
2842 public Intent getConfigurationIntent(String transportName) {
2843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2844 "getConfigurationIntent");
2845
2846 synchronized (mTransports) {
2847 final IBackupTransport transport = mTransports.get(transportName);
2848 if (transport != null) {
2849 try {
2850 final Intent intent = transport.configurationIntent();
2851 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2852 + intent);
2853 return intent;
2854 } catch (RemoteException e) {
2855 /* fall through to return null */
2856 }
2857 }
2858 }
2859
2860 return null;
2861 }
2862
2863 // Supply the configuration summary string for the given transport. If the name is
2864 // not one of the available transports, or if the transport does not supply any
2865 // summary / destination string, the method can return null.
2866 //
2867 // This string is used VERBATIM as the summary text of the relevant Settings item!
2868 public String getDestinationString(String transportName) {
2869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2870 "getConfigurationIntent");
2871
2872 synchronized (mTransports) {
2873 final IBackupTransport transport = mTransports.get(transportName);
2874 if (transport != null) {
2875 try {
2876 final String text = transport.currentDestinationString();
2877 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2878 return text;
2879 } catch (RemoteException e) {
2880 /* fall through to return null */
2881 }
2882 }
2883 }
2884
2885 return null;
2886 }
2887
Christopher Tate043dadc2009-06-02 16:11:00 -07002888 // Callback: a requested backup agent has been instantiated. This should only
2889 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002890 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002891 synchronized(mAgentConnectLock) {
2892 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002893 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002894 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2895 mConnectedAgent = agent;
2896 mConnecting = false;
2897 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002898 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002899 + " claiming agent connected");
2900 }
2901 mAgentConnectLock.notifyAll();
2902 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002903 }
2904
2905 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2906 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002907 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002908 public void agentDisconnected(String packageName) {
2909 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002910 synchronized(mAgentConnectLock) {
2911 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2912 mConnectedAgent = null;
2913 mConnecting = false;
2914 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002915 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002916 + " claiming agent disconnected");
2917 }
2918 mAgentConnectLock.notifyAll();
2919 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002920 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002921
Christopher Tate1bb69062010-02-19 17:02:12 -08002922 // An application being installed will need a restore pass, then the Package Manager
2923 // will need to be told when the restore is finished.
2924 public void restoreAtInstall(String packageName, int token) {
2925 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002926 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002927 + " attemping install-time restore");
2928 return;
2929 }
2930
2931 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002932 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002933 + " token=" + Integer.toHexString(token));
2934
Christopher Tatef0872722010-02-25 15:22:48 -08002935 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002936 // okay, we're going to attempt a restore of this package from this restore set.
2937 // The eventual message back into the Package Manager to run the post-install
2938 // steps for 'token' will be issued from the restore handling code.
2939
2940 // We can use a synthetic PackageInfo here because:
2941 // 1. We know it's valid, since the Package Manager supplied the name
2942 // 2. Only the packageName field will be used by the restore code
2943 PackageInfo pkg = new PackageInfo();
2944 pkg.packageName = packageName;
2945
2946 mWakelock.acquire();
2947 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2948 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002949 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002950 mBackupHandler.sendMessage(msg);
2951 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002952 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2953 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002954 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002955 try {
2956 mPackageManagerBinder.finishPackageInstall(token);
2957 } catch (RemoteException e) { /* can't happen */ }
2958 }
2959 }
2960
Christopher Tate8c850b72009-06-07 19:33:20 -07002961 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002962 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2963 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2964 + " transport=" + transport);
2965
2966 boolean needPermission = true;
2967 if (transport == null) {
2968 transport = mCurrentTransport;
2969
2970 if (packageName != null) {
2971 PackageInfo app = null;
2972 try {
2973 app = mPackageManager.getPackageInfo(packageName, 0);
2974 } catch (NameNotFoundException nnf) {
2975 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2976 throw new IllegalArgumentException("Package " + packageName + " not found");
2977 }
2978
2979 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2980 // So: using the current active transport, and the caller has asked
2981 // that its own package will be restored. In this narrow use case
2982 // we do not require the caller to hold the permission.
2983 needPermission = false;
2984 }
2985 }
2986 }
2987
2988 if (needPermission) {
2989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2990 "beginRestoreSession");
2991 } else {
2992 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2993 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002994
2995 synchronized(this) {
2996 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002997 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002998 return null;
2999 }
Chris Tate44ab8452010-11-16 15:10:49 -08003000 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08003001 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07003002 }
3003 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07003004 }
Christopher Tate043dadc2009-06-02 16:11:00 -07003005
Christopher Tate73a3cb32010-12-13 18:27:26 -08003006 void clearRestoreSession(ActiveRestoreSession currentSession) {
3007 synchronized(this) {
3008 if (currentSession != mActiveRestoreSession) {
3009 Slog.e(TAG, "ending non-current restore session");
3010 } else {
3011 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
3012 mActiveRestoreSession = null;
3013 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3014 }
3015 }
3016 }
3017
Christopher Tate44a27902010-01-27 17:15:49 -08003018 // Note that a currently-active backup agent has notified us that it has
3019 // completed the given outstanding asynchronous backup/restore operation.
3020 public void opComplete(int token) {
3021 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003022 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08003023 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
3024 mCurrentOpLock.notifyAll();
3025 }
3026 }
3027
Christopher Tate9b3905c2009-06-08 15:24:01 -07003028 // ----- Restore session -----
3029
Christopher Tate80202c82010-01-25 19:37:47 -08003030 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07003031 private static final String TAG = "RestoreSession";
3032
Chris Tate44ab8452010-11-16 15:10:49 -08003033 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003034 private IBackupTransport mRestoreTransport = null;
3035 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08003036 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003037
Chris Tate44ab8452010-11-16 15:10:49 -08003038 ActiveRestoreSession(String packageName, String transport) {
3039 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07003040 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07003041 }
3042
3043 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07003044 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04003045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003046 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003047 if (observer == null) {
3048 throw new IllegalArgumentException("Observer must not be null");
3049 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003050
Christopher Tate73a3cb32010-12-13 18:27:26 -08003051 if (mEnded) {
3052 throw new IllegalStateException("Restore session already ended");
3053 }
3054
Christopher Tate1bb69062010-02-19 17:02:12 -08003055 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07003056 try {
Christopher Tate43383042009-07-13 15:17:13 -07003057 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003058 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003059 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07003060 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07003061 // spin off the transport request to our service thread
3062 mWakelock.acquire();
3063 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
3064 new RestoreGetSetsParams(mRestoreTransport, this, observer));
3065 mBackupHandler.sendMessage(msg);
3066 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07003067 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003068 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07003069 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08003070 } finally {
3071 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07003072 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07003073 }
3074
Christopher Tate84725812010-02-04 15:52:40 -08003075 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07003076 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3077 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003078
Chris Tate44ab8452010-11-16 15:10:49 -08003079 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07003080 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003081
Christopher Tate73a3cb32010-12-13 18:27:26 -08003082 if (mEnded) {
3083 throw new IllegalStateException("Restore session already ended");
3084 }
3085
Dan Egnor0084da52009-07-29 12:57:16 -07003086 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08003087 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
3088 return -1;
3089 }
3090
3091 if (mPackageName != null) {
3092 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07003093 return -1;
3094 }
3095
Christopher Tate21ab6a52009-09-24 18:01:46 -07003096 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003097 for (int i = 0; i < mRestoreSets.length; i++) {
3098 if (token == mRestoreSets[i].token) {
3099 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07003100 mWakelock.acquire();
3101 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003102 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07003103 mBackupHandler.sendMessage(msg);
3104 Binder.restoreCallingIdentity(oldId);
3105 return 0;
3106 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003107 }
3108 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07003109
Joe Onorato8a9b2202010-02-26 18:56:32 -08003110 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07003111 return -1;
3112 }
3113
Christopher Tate84725812010-02-04 15:52:40 -08003114 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003115 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08003116
Christopher Tate73a3cb32010-12-13 18:27:26 -08003117 if (mEnded) {
3118 throw new IllegalStateException("Restore session already ended");
3119 }
3120
Chris Tate44ab8452010-11-16 15:10:49 -08003121 if (mPackageName != null) {
3122 if (! mPackageName.equals(packageName)) {
3123 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
3124 + " on session for package " + mPackageName);
3125 return -1;
3126 }
3127 }
3128
Christopher Tate84725812010-02-04 15:52:40 -08003129 PackageInfo app = null;
3130 try {
3131 app = mPackageManager.getPackageInfo(packageName, 0);
3132 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003133 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003134 return -1;
3135 }
3136
3137 // If the caller is not privileged and is not coming from the target
3138 // app's uid, throw a permission exception back to the caller.
3139 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
3140 Binder.getCallingPid(), Binder.getCallingUid());
3141 if ((perm == PackageManager.PERMISSION_DENIED) &&
3142 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003143 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08003144 + " or calling uid=" + Binder.getCallingUid());
3145 throw new SecurityException("No permission to restore other packages");
3146 }
3147
Christopher Tate7d411a32010-02-26 11:27:08 -08003148 // If the package has no backup agent, we obviously cannot proceed
3149 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003150 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08003151 return -1;
3152 }
3153
Christopher Tate84725812010-02-04 15:52:40 -08003154 // So far so good; we're allowed to try to restore this package. Now
3155 // check whether there is data for it in the current dataset, falling back
3156 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08003157 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003158
3159 // If we didn't come up with a place to look -- no ancestral dataset and
3160 // the app has never been backed up from this device -- there's nothing
3161 // to do but return failure.
3162 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08003163 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08003164 return -1;
3165 }
3166
3167 // Ready to go: enqueue the restore request and claim success
3168 long oldId = Binder.clearCallingIdentity();
3169 mWakelock.acquire();
3170 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003171 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08003172 mBackupHandler.sendMessage(msg);
3173 Binder.restoreCallingIdentity(oldId);
3174 return 0;
3175 }
3176
Christopher Tate73a3cb32010-12-13 18:27:26 -08003177 // Posted to the handler to tear down a restore session in a cleanly synchronized way
3178 class EndRestoreRunnable implements Runnable {
3179 BackupManagerService mBackupManager;
3180 ActiveRestoreSession mSession;
3181
3182 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
3183 mBackupManager = manager;
3184 mSession = session;
3185 }
3186
3187 public void run() {
3188 // clean up the session's bookkeeping
3189 synchronized (mSession) {
3190 try {
3191 if (mSession.mRestoreTransport != null) {
3192 mSession.mRestoreTransport.finishRestore();
3193 }
3194 } catch (Exception e) {
3195 Slog.e(TAG, "Error in finishRestore", e);
3196 } finally {
3197 mSession.mRestoreTransport = null;
3198 mSession.mEnded = true;
3199 }
3200 }
3201
3202 // clean up the BackupManagerService side of the bookkeeping
3203 // and cancel any pending timeout message
3204 mBackupManager.clearRestoreSession(mSession);
3205 }
3206 }
3207
Dan Egnor0084da52009-07-29 12:57:16 -07003208 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003209 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003210
Christopher Tate73a3cb32010-12-13 18:27:26 -08003211 if (mEnded) {
3212 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07003213 }
3214
Christopher Tate73a3cb32010-12-13 18:27:26 -08003215 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07003216 }
3217 }
3218
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003219 @Override
3220 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003221 long identityToken = Binder.clearCallingIdentity();
3222 try {
3223 dumpInternal(pw);
3224 } finally {
3225 Binder.restoreCallingIdentity(identityToken);
3226 }
3227 }
3228
3229 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003230 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07003231 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07003232 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08003233 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08003234 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07003235 pw.println("Last backup pass: " + mLastBackupPass
3236 + " (now = " + System.currentTimeMillis() + ')');
3237 pw.println(" next scheduled: " + mNextBackupPass);
3238
Christopher Tate91717492009-06-26 21:07:13 -07003239 pw.println("Available transports:");
3240 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003241 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
3242 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003243 IBackupTransport transport = getTransport(t);
3244 File dir = new File(mBaseStateDir, transport.transportDirName());
3245 pw.println(" destination: " + transport.currentDestinationString());
3246 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07003247 for (File f : dir.listFiles()) {
3248 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
3249 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003250 } catch (Exception e) {
3251 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003252 pw.println(" Error: " + e);
3253 }
Christopher Tate91717492009-06-26 21:07:13 -07003254 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003255
3256 pw.println("Pending init: " + mPendingInits.size());
3257 for (String s : mPendingInits) {
3258 pw.println(" " + s);
3259 }
3260
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003261 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07003262 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003263 for (int i=0; i<N; i++) {
3264 int uid = mBackupParticipants.keyAt(i);
3265 pw.print(" uid: ");
3266 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003267 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
3268 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07003269 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003270 }
3271 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003272
Christopher Tateb49ceb32010-02-08 16:22:24 -08003273 pw.println("Ancestral packages: "
3274 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07003275 if (mAncestralPackages != null) {
3276 for (String pkg : mAncestralPackages) {
3277 pw.println(" " + pkg);
3278 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08003279 }
3280
Christopher Tate73e02522009-07-15 14:18:26 -07003281 pw.println("Ever backed up: " + mEverStoredApps.size());
3282 for (String pkg : mEverStoredApps) {
3283 pw.println(" " + pkg);
3284 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003285
3286 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07003287 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07003288 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07003289 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003290 }
3291 }
Christopher Tate487529a2009-04-29 14:03:25 -07003292}