blob: 7c6d3c144346b62b9b31e2835dccfb3e06cd7fe6 [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 Tatea858cb02011-06-03 12:27:51 -070042import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070043import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080044import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070045import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070046import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060047import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060048import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070049import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070050import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070051import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070052import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070053import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070054import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080055import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070056import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080057import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070058import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070059import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070060import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070062import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070063import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070064import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080065import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070066import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070068import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080069import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070070import android.util.StringBuilderPrinter;
71
Jason parksa3cdaa52011-01-13 14:15:43 -060072import com.android.internal.backup.BackupConstants;
73import com.android.internal.backup.IBackupTransport;
74import com.android.internal.backup.LocalTransport;
75import com.android.server.PackageManagerBackupAgent.Metadata;
76
Christopher Tatecde87f42009-06-12 12:55:53 -070077import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070078import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070079import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070080import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080081import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070082import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070083import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070084import java.io.InputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070085import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070086import java.io.RandomAccessFile;
Christopher Tate75a99702011-05-18 16:28:19 -070087import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -040088import java.util.ArrayList;
Christopher Tate75a99702011-05-18 16:28:19 -070089import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -040090import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070091import java.util.HashSet;
92import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070093import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070094import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080095import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -070096import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate487529a2009-04-29 14:03:25 -070097
98class BackupManagerService extends IBackupManager.Stub {
99 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700100 private static final boolean DEBUG = true;
101
102 // Name and current contents version of the full-backup manifest file
103 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
104 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -0700105
Christopher Tate49401dd2009-07-01 12:34:29 -0700106 // How often we perform a backup pass. Privileged external callers can
107 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700108 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700109
Dan Egnorc1c49c02009-10-30 17:35:39 -0700110 // Random variation in backup scheduling time to avoid server load spikes
111 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
112
Christopher Tate8031a3d2009-07-06 16:36:05 -0700113 // The amount of time between the initial provisioning of the device and
114 // the first backup pass.
115 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
116
Christopher Tate45281862010-03-05 15:46:30 -0800117 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
118 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
119 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700120 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700121 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700122 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700123 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700124 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700125 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
126 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800127 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700128 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
129 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700130
131 // Timeout interval for deciding that a bind or clear-data has taken too long
132 static final long TIMEOUT_INTERVAL = 10 * 1000;
133
Christopher Tate44a27902010-01-27 17:15:49 -0800134 // Timeout intervals for agent backup & restore operations
135 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700136 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800137 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
138
Christopher Tate4a627c72011-04-01 14:43:32 -0700139 // User confirmation timeout for a full backup/restore operation
140 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
141
Christopher Tate487529a2009-04-29 14:03:25 -0700142 private Context mContext;
143 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800144 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700145 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700146 private PowerManager mPowerManager;
147 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800148 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700149
Christopher Tate73e02522009-07-15 14:18:26 -0700150 boolean mEnabled; // access to this is synchronized on 'this'
151 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800152 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700153 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800154 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
155 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700156 PendingIntent mRunBackupIntent, mRunInitIntent;
157 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700158 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700159 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700160 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700161 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700162 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700163 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700164
Christopher Tate4a627c72011-04-01 14:43:32 -0700165 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700166 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700167 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700168
169 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700170 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700171 }
Christopher Tate46758122009-05-06 11:22:00 -0700172 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800173 // Backups that we haven't started yet. Keys are package names.
174 HashMap<String,BackupRequest> mPendingBackups
175 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700176
177 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700178 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700179
180 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700181 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700182
Christopher Tate043dadc2009-06-02 16:11:00 -0700183 // The thread performing the sequence of queued backups binds to each app's agent
184 // in succession. Bind notifications are asynchronously delivered through the
185 // Activity Manager; use this lock object to signal when a requested binding has
186 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700187 final Object mAgentConnectLock = new Object();
188 IBackupAgent mConnectedAgent;
189 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700190 volatile long mLastBackupPass;
191 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700192
Christopher Tate55f931a2009-09-29 17:17:34 -0700193 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700194 final Object mClearDataLock = new Object();
195 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700196
Christopher Tate91717492009-06-26 21:07:13 -0700197 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700198 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700199 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700200 String mCurrentTransport;
201 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800202 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700203
Christopher Tate2d449afe2010-03-29 19:14:24 -0700204 class RestoreGetSetsParams {
205 public IBackupTransport transport;
206 public ActiveRestoreSession session;
207 public IRestoreObserver observer;
208
209 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
210 IRestoreObserver _observer) {
211 transport = _transport;
212 session = _session;
213 observer = _observer;
214 }
215 }
216
Christopher Tate73e02522009-07-15 14:18:26 -0700217 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700218 public IBackupTransport transport;
219 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700220 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800221 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800222 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700223 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800224
225 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700226 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800227 transport = _transport;
228 observer = _obs;
229 token = _token;
230 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800231 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700232 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800233 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700234
Chris Tate249345b2010-10-29 12:57:04 -0700235 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
236 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700237 transport = _transport;
238 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700239 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800240 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800241 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700242 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700243 }
244 }
245
Christopher Tate73e02522009-07-15 14:18:26 -0700246 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700247 public IBackupTransport transport;
248 public PackageInfo packageInfo;
249
250 ClearParams(IBackupTransport _transport, PackageInfo _info) {
251 transport = _transport;
252 packageInfo = _info;
253 }
254 }
255
Christopher Tate4a627c72011-04-01 14:43:32 -0700256 class FullParams {
257 public ParcelFileDescriptor fd;
258 public final AtomicBoolean latch;
259 public IFullBackupRestoreObserver observer;
260
261 FullParams() {
262 latch = new AtomicBoolean(false);
263 }
264 }
265
266 class FullBackupParams extends FullParams {
267 public boolean includeApks;
268 public boolean includeShared;
269 public boolean allApps;
270 public String[] packages;
271
272 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
273 boolean doAllApps, String[] pkgList) {
274 fd = output;
275 includeApks = saveApks;
276 includeShared = saveShared;
277 allApps = doAllApps;
278 packages = pkgList;
279 }
280 }
281
282 class FullRestoreParams extends FullParams {
283 FullRestoreParams(ParcelFileDescriptor input) {
284 fd = input;
285 }
286 }
287
Christopher Tate44a27902010-01-27 17:15:49 -0800288 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
289 // token is the index of the entry in the pending-operations list.
290 static final int OP_PENDING = 0;
291 static final int OP_ACKNOWLEDGED = 1;
292 static final int OP_TIMEOUT = -1;
293
294 final SparseIntArray mCurrentOperations = new SparseIntArray();
295 final Object mCurrentOpLock = new Object();
296 final Random mTokenGenerator = new Random();
297
Christopher Tate4a627c72011-04-01 14:43:32 -0700298 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
299
Christopher Tate5cb400b2009-06-25 16:03:14 -0700300 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700301 File mBaseStateDir;
302 File mDataDir;
303 File mJournalDir;
304 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700305
Christopher Tate84725812010-02-04 15:52:40 -0800306 // Keep a log of all the apps we've ever backed up, and what the
307 // dataset tokens are for both the current backup dataset and
308 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700309 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700310 HashSet<String> mEverStoredApps = new HashSet<String>();
311
Christopher Tateb49ceb32010-02-08 16:22:24 -0800312 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800313 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800314 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800315 long mAncestralToken = 0;
316 long mCurrentToken = 0;
317
Christopher Tate4cc86e12009-09-21 19:36:51 -0700318 // Persistently track the need to do a full init
319 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
320 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700321
Christopher Tate4a627c72011-04-01 14:43:32 -0700322 // Utility: build a new random integer token
323 int generateToken() {
324 int token;
325 do {
326 synchronized (mTokenGenerator) {
327 token = mTokenGenerator.nextInt();
328 }
329 } while (token < 0);
330 return token;
331 }
332
Christopher Tate44a27902010-01-27 17:15:49 -0800333 // ----- Asynchronous backup/restore handler thread -----
334
335 private class BackupHandler extends Handler {
336 public BackupHandler(Looper looper) {
337 super(looper);
338 }
339
340 public void handleMessage(Message msg) {
341
342 switch (msg.what) {
343 case MSG_RUN_BACKUP:
344 {
345 mLastBackupPass = System.currentTimeMillis();
346 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
347
348 IBackupTransport transport = getTransport(mCurrentTransport);
349 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800350 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800351 mWakelock.release();
352 break;
353 }
354
355 // snapshot the pending-backup set and work on that
356 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800357 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800358 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800359 // Do we have any work to do? Construct the work queue
360 // then release the synchronization lock to actually run
361 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800362 if (mPendingBackups.size() > 0) {
363 for (BackupRequest b: mPendingBackups.values()) {
364 queue.add(b);
365 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800366 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800367 mPendingBackups.clear();
368
369 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800370 mJournal = null;
371
Christopher Tate44a27902010-01-27 17:15:49 -0800372 }
373 }
Christopher Tatec61da312010-02-05 10:41:27 -0800374
375 if (queue.size() > 0) {
376 // At this point, we have started a new journal file, and the old
377 // file identity is being passed to the backup processing thread.
378 // When it completes successfully, that old journal file will be
379 // deleted. If we crash prior to that, the old journal is parsed
380 // at next boot and the journaled requests fulfilled.
381 (new PerformBackupTask(transport, queue, oldJournal)).run();
382 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800383 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800384 mWakelock.release();
385 }
Christopher Tate44a27902010-01-27 17:15:49 -0800386 break;
387 }
388
389 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700390 {
391 FullBackupParams params = (FullBackupParams)msg.obj;
392 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
393 params.includeShared, params.allApps, params.packages,
394 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800395 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700396 }
Christopher Tate44a27902010-01-27 17:15:49 -0800397
398 case MSG_RUN_RESTORE:
399 {
400 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800401 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800402 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700403 params.token, params.pkgInfo, params.pmToken,
404 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800405 break;
406 }
407
Christopher Tate75a99702011-05-18 16:28:19 -0700408 case MSG_RUN_FULL_RESTORE:
409 {
410 FullRestoreParams params = (FullRestoreParams)msg.obj;
411 (new PerformFullRestoreTask(params.fd, params.observer, params.latch)).run();
412 break;
413 }
414
Christopher Tate44a27902010-01-27 17:15:49 -0800415 case MSG_RUN_CLEAR:
416 {
417 ClearParams params = (ClearParams)msg.obj;
418 (new PerformClearTask(params.transport, params.packageInfo)).run();
419 break;
420 }
421
422 case MSG_RUN_INITIALIZE:
423 {
424 HashSet<String> queue;
425
426 // Snapshot the pending-init queue and work on that
427 synchronized (mQueueLock) {
428 queue = new HashSet<String>(mPendingInits);
429 mPendingInits.clear();
430 }
431
432 (new PerformInitializeTask(queue)).run();
433 break;
434 }
435
Christopher Tate2d449afe2010-03-29 19:14:24 -0700436 case MSG_RUN_GET_RESTORE_SETS:
437 {
438 // Like other async operations, this is entered with the wakelock held
439 RestoreSet[] sets = null;
440 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
441 try {
442 sets = params.transport.getAvailableRestoreSets();
443 // cache the result in the active session
444 synchronized (params.session) {
445 params.session.mRestoreSets = sets;
446 }
447 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
448 } catch (Exception e) {
449 Slog.e(TAG, "Error from transport getting set list");
450 } finally {
451 if (params.observer != null) {
452 try {
453 params.observer.restoreSetsAvailable(sets);
454 } catch (RemoteException re) {
455 Slog.e(TAG, "Unable to report listing to observer");
456 } catch (Exception e) {
457 Slog.e(TAG, "Restore observer threw", e);
458 }
459 }
460
Christopher Tate2a935092011-03-03 17:30:32 -0800461 // Done: reset the session timeout clock
462 removeMessages(MSG_RESTORE_TIMEOUT);
463 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
464
Christopher Tate2d449afe2010-03-29 19:14:24 -0700465 mWakelock.release();
466 }
467 break;
468 }
469
Christopher Tate44a27902010-01-27 17:15:49 -0800470 case MSG_TIMEOUT:
471 {
472 synchronized (mCurrentOpLock) {
473 final int token = msg.arg1;
474 int state = mCurrentOperations.get(token, OP_TIMEOUT);
475 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800476 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800477 mCurrentOperations.put(token, OP_TIMEOUT);
478 }
479 mCurrentOpLock.notifyAll();
480 }
481 break;
482 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800483
484 case MSG_RESTORE_TIMEOUT:
485 {
486 synchronized (BackupManagerService.this) {
487 if (mActiveRestoreSession != null) {
488 // Client app left the restore session dangling. We know that it
489 // can't be in the middle of an actual restore operation because
490 // those are executed serially on this same handler thread. Clean
491 // up now.
492 Slog.w(TAG, "Restore session timed out; aborting");
493 post(mActiveRestoreSession.new EndRestoreRunnable(
494 BackupManagerService.this, mActiveRestoreSession));
495 }
496 }
497 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700498
499 case MSG_FULL_CONFIRMATION_TIMEOUT:
500 {
501 synchronized (mFullConfirmations) {
502 FullParams params = mFullConfirmations.get(msg.arg1);
503 if (params != null) {
504 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
505
506 // Release the waiter; timeout == completion
507 signalFullBackupRestoreCompletion(params);
508
509 // Remove the token from the set
510 mFullConfirmations.delete(msg.arg1);
511
512 // Report a timeout to the observer, if any
513 if (params.observer != null) {
514 try {
515 params.observer.onTimeout();
516 } catch (RemoteException e) {
517 /* don't care if the app has gone away */
518 }
519 }
520 } else {
521 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
522 }
523 }
524 break;
525 }
Christopher Tate44a27902010-01-27 17:15:49 -0800526 }
527 }
528 }
529
530 // ----- Main service implementation -----
531
Christopher Tate487529a2009-04-29 14:03:25 -0700532 public BackupManagerService(Context context) {
533 mContext = context;
534 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700535 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700536 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700537
Christopher Tateb6787f22009-07-02 17:40:45 -0700538 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
539 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
540
Christopher Tate44a27902010-01-27 17:15:49 -0800541 mBackupManagerBinder = asInterface(asBinder());
542
543 // spin up the backup/restore handler thread
544 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
545 mHandlerThread.start();
546 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
547
Christopher Tate22b87872009-05-04 16:41:53 -0700548 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700549 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700550 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700551 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700552 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800553 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800554 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800555 // If Encrypted file systems is enabled or disabled, this call will return the
556 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600557 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800558 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700559 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700560
Christopher Tate4cc86e12009-09-21 19:36:51 -0700561 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700562 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700563 IntentFilter filter = new IntentFilter();
564 filter.addAction(RUN_BACKUP_ACTION);
565 context.registerReceiver(mRunBackupReceiver, filter,
566 android.Manifest.permission.BACKUP, null);
567
568 mRunInitReceiver = new RunInitializeReceiver();
569 filter = new IntentFilter();
570 filter.addAction(RUN_INITIALIZE_ACTION);
571 context.registerReceiver(mRunInitReceiver, filter,
572 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700573
574 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700575 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
576 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
577
Christopher Tate4cc86e12009-09-21 19:36:51 -0700578 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
579 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
580 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
581
Christopher Tatecde87f42009-06-12 12:55:53 -0700582 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700583 mJournalDir = new File(mBaseStateDir, "pending");
584 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700585 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700586
Christopher Tate73e02522009-07-15 14:18:26 -0700587 // Set up the various sorts of package tracking we do
588 initPackageTracking();
589
Christopher Tateabce4e82009-06-18 18:35:32 -0700590 // Build our mapping of uid to backup client services. This implicitly
591 // schedules a backup pass on the Package Manager metadata the first
592 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700593 synchronized (mBackupParticipants) {
594 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700595 }
596
Dan Egnor87a02bc2009-06-17 02:30:10 -0700597 // Set up our transport options and initialize the default transport
598 // TODO: Have transports register themselves somehow?
599 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700600 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700601 ComponentName localName = new ComponentName(context, LocalTransport.class);
602 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700603
Christopher Tate91717492009-06-26 21:07:13 -0700604 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700605 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
606 Settings.Secure.BACKUP_TRANSPORT);
607 if ("".equals(mCurrentTransport)) {
608 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700609 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800610 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700611
612 // Attach to the Google backup transport. When this comes up, it will set
613 // itself as the current transport because we explicitly reset mCurrentTransport
614 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700615 ComponentName transportComponent = new ComponentName("com.google.android.backup",
616 "com.google.android.backup.BackupTransportService");
617 try {
618 // If there's something out there that is supposed to be the Google
619 // backup transport, make sure it's legitimately part of the OS build
620 // and not an app lying about its package name.
621 ApplicationInfo info = mPackageManager.getApplicationInfo(
622 transportComponent.getPackageName(), 0);
623 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
624 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
625 Intent intent = new Intent().setComponent(transportComponent);
626 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
627 } else {
628 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
629 }
630 } catch (PackageManager.NameNotFoundException nnf) {
631 // No such package? No binding.
632 if (DEBUG) Slog.v(TAG, "Google transport not present");
633 }
Christopher Tateaa088442009-06-16 18:25:46 -0700634
Christopher Tatecde87f42009-06-12 12:55:53 -0700635 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700636 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700637 parseLeftoverJournals();
638
Christopher Tateb6787f22009-07-02 17:40:45 -0700639 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700640 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700641
642 // Start the backup passes going
643 setBackupEnabled(areEnabled);
644 }
645
646 private class RunBackupReceiver extends BroadcastReceiver {
647 public void onReceive(Context context, Intent intent) {
648 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700649 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700650 if (mPendingInits.size() > 0) {
651 // If there are pending init operations, we process those
652 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700654 try {
655 mAlarmManager.cancel(mRunInitIntent);
656 mRunInitIntent.send();
657 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800658 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700659 // can't really do more than bail here
660 }
661 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800662 // Don't run backups now if we're disabled or not yet
663 // fully set up.
664 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800665 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700666
667 // Acquire the wakelock and pass it to the backup thread. it will
668 // be released once backup concludes.
669 mWakelock.acquire();
670
671 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
672 mBackupHandler.sendMessage(msg);
673 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675 }
676 }
677 }
678 }
679 }
680 }
681
682 private class RunInitializeReceiver extends BroadcastReceiver {
683 public void onReceive(Context context, Intent intent) {
684 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
685 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800686 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700687
688 // Acquire the wakelock and pass it to the init thread. it will
689 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700690 mWakelock.acquire();
691
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700693 mBackupHandler.sendMessage(msg);
694 }
695 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700696 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700697 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700698
Christopher Tate73e02522009-07-15 14:18:26 -0700699 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800700 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700701
Christopher Tate84725812010-02-04 15:52:40 -0800702 // Remember our ancestral dataset
703 mTokenFile = new File(mBaseStateDir, "ancestral");
704 try {
705 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800706 int version = tf.readInt();
707 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
708 mAncestralToken = tf.readLong();
709 mCurrentToken = tf.readLong();
710
711 int numPackages = tf.readInt();
712 if (numPackages >= 0) {
713 mAncestralPackages = new HashSet<String>();
714 for (int i = 0; i < numPackages; i++) {
715 String pkgName = tf.readUTF();
716 mAncestralPackages.add(pkgName);
717 }
718 }
719 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800720 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800721 } catch (FileNotFoundException fnf) {
722 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800723 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800724 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800725 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800726 }
727
Christopher Tatee97e8072009-07-15 16:45:50 -0700728 // Keep a log of what apps we've ever backed up. Because we might have
729 // rebooted in the middle of an operation that was removing something from
730 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700731 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700732 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700733
Christopher Tatee97e8072009-07-15 16:45:50 -0700734 // If we were in the middle of removing something from the ever-backed-up
735 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700736 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700737 if (tempProcessedFile.exists()) {
738 tempProcessedFile.delete();
739 }
740
Dan Egnor852f8e42009-09-30 11:20:45 -0700741 // If there are previous contents, parse them out then start a new
742 // file to continue the recordkeeping.
743 if (mEverStored.exists()) {
744 RandomAccessFile temp = null;
745 RandomAccessFile in = null;
746
747 try {
748 temp = new RandomAccessFile(tempProcessedFile, "rws");
749 in = new RandomAccessFile(mEverStored, "r");
750
751 while (true) {
752 PackageInfo info;
753 String pkg = in.readUTF();
754 try {
755 info = mPackageManager.getPackageInfo(pkg, 0);
756 mEverStoredApps.add(pkg);
757 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800758 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700759 } catch (NameNotFoundException e) {
760 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800761 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700762 }
763 }
764 } catch (EOFException e) {
765 // Once we've rewritten the backup history log, atomically replace the
766 // old one with the new one then reopen the file for continuing use.
767 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800768 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700769 }
770 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800771 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700772 } finally {
773 try { if (temp != null) temp.close(); } catch (IOException e) {}
774 try { if (in != null) in.close(); } catch (IOException e) {}
775 }
776 }
777
Christopher Tate73e02522009-07-15 14:18:26 -0700778 // Register for broadcasts about package install, etc., so we can
779 // update the provider list.
780 IntentFilter filter = new IntentFilter();
781 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
782 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
783 filter.addDataScheme("package");
784 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800785 // Register for events related to sdcard installation.
786 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800787 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
788 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800789 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700790 }
791
Christopher Tatecde87f42009-06-12 12:55:53 -0700792 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700793 for (File f : mJournalDir.listFiles()) {
794 if (mJournal == null || f.compareTo(mJournal) != 0) {
795 // This isn't the current journal, so it must be a leftover. Read
796 // out the package names mentioned there and schedule them for
797 // backup.
798 RandomAccessFile in = null;
799 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400800 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700801 in = new RandomAccessFile(f, "r");
802 while (true) {
803 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400804 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700805 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700806 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700807 } catch (EOFException e) {
808 // no more data; we're done
809 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800810 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700811 } finally {
812 // close/delete the file
813 try { if (in != null) in.close(); } catch (IOException e) {}
814 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700815 }
816 }
817 }
818 }
819
Christopher Tate4cc86e12009-09-21 19:36:51 -0700820 // Maintain persistent state around whether need to do an initialize operation.
821 // Must be called with the queue lock held.
822 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700824 + " on transport " + transportName);
825 try {
826 IBackupTransport transport = getTransport(transportName);
827 String transportDirName = transport.transportDirName();
828 File stateDir = new File(mBaseStateDir, transportDirName);
829 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
830
831 if (isPending) {
832 // We need an init before we can proceed with sending backup data.
833 // Record that with an entry in our set of pending inits, as well as
834 // journaling it via creation of a sentinel file.
835 mPendingInits.add(transportName);
836 try {
837 (new FileOutputStream(initPendingFile)).close();
838 } catch (IOException ioe) {
839 // Something is badly wrong with our permissions; just try to move on
840 }
841 } else {
842 // No more initialization needed; wipe the journal and reset our state.
843 initPendingFile.delete();
844 mPendingInits.remove(transportName);
845 }
846 } catch (RemoteException e) {
847 // can't happen; the transport is local
848 }
849 }
850
Christopher Tated55e18a2009-09-21 10:12:59 -0700851 // Reset all of our bookkeeping, in response to having been told that
852 // the backend data has been wiped [due to idle expiry, for example],
853 // so we must re-upload all saved settings.
854 void resetBackupState(File stateFileDir) {
855 synchronized (mQueueLock) {
856 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700857 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700858 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700859
Christopher Tate84725812010-02-04 15:52:40 -0800860 mCurrentToken = 0;
861 writeRestoreTokens();
862
Christopher Tated55e18a2009-09-21 10:12:59 -0700863 // Remove all the state files
864 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700865 // ... but don't touch the needs-init sentinel
866 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
867 sf.delete();
868 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700869 }
Christopher Tate45597642011-04-04 16:59:21 -0700870 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700871
Christopher Tate45597642011-04-04 16:59:21 -0700872 // Enqueue a new backup of every participant
873 int N = mBackupParticipants.size();
874 for (int i=0; i<N; i++) {
875 int uid = mBackupParticipants.keyAt(i);
876 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
877 for (ApplicationInfo app: participants) {
878 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700879 }
880 }
881 }
882
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800883 // Add a transport to our set of available backends. If 'transport' is null, this
884 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700885 private void registerTransport(String name, IBackupTransport transport) {
886 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800887 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800888 if (transport != null) {
889 mTransports.put(name, transport);
890 } else {
891 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800892 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800893 mCurrentTransport = null;
894 }
895 // Nothing further to do in the unregistration case
896 return;
897 }
Christopher Tate91717492009-06-26 21:07:13 -0700898 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700899
900 // If the init sentinel file exists, we need to be sure to perform the init
901 // as soon as practical. We also create the state directory at registration
902 // time to ensure it's present from the outset.
903 try {
904 String transportName = transport.transportDirName();
905 File stateDir = new File(mBaseStateDir, transportName);
906 stateDir.mkdirs();
907
908 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
909 if (initSentinel.exists()) {
910 synchronized (mQueueLock) {
911 mPendingInits.add(transportName);
912
913 // TODO: pick a better starting time than now + 1 minute
914 long delay = 1000 * 60; // one minute, in milliseconds
915 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
916 System.currentTimeMillis() + delay, mRunInitIntent);
917 }
918 }
919 } catch (RemoteException e) {
920 // can't happen, the transport is local
921 }
Christopher Tate91717492009-06-26 21:07:13 -0700922 }
923
Christopher Tate3799bc22009-05-06 16:13:56 -0700924 // ----- Track installation/removal of packages -----
925 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
926 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800927 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700928
Christopher Tate3799bc22009-05-06 16:13:56 -0700929 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800930 boolean replacing = false;
931 boolean added = false;
932 Bundle extras = intent.getExtras();
933 String pkgList[] = null;
934 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
935 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
936 Uri uri = intent.getData();
937 if (uri == null) {
938 return;
939 }
940 String pkgName = uri.getSchemeSpecificPart();
941 if (pkgName != null) {
942 pkgList = new String[] { pkgName };
943 }
944 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
945 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800946 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800947 added = true;
948 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800949 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800950 added = false;
951 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
952 }
953 if (pkgList == null || pkgList.length == 0) {
954 return;
955 }
956 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700957 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800958 for (String pkgName : pkgList) {
959 if (replacing) {
960 // The package was just upgraded
961 updatePackageParticipantsLocked(pkgName);
962 } else {
963 // The package was just added
964 addPackageParticipantsLocked(pkgName);
965 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700966 }
967 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800968 } else {
969 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700970 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
971 } else {
972 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800973 for (String pkgName : pkgList) {
974 removePackageParticipantsLocked(pkgName);
975 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700976 }
977 }
978 }
979 }
980 };
981
Dan Egnor87a02bc2009-06-17 02:30:10 -0700982 // ----- Track connection to GoogleBackupTransport service -----
983 ServiceConnection mGoogleConnection = new ServiceConnection() {
984 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800985 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700986 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700987 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700988 }
989
990 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700992 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700993 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700994 }
995 };
996
Christopher Tate181fafa2009-05-14 11:12:14 -0700997 // Add the backup agents in the given package to our set of known backup participants.
998 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700999 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001000 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001001 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001002 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001003 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001004 }
1005
Christopher Tate181fafa2009-05-14 11:12:14 -07001006 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001007 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001008 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001009 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001010 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001011 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001012 + " uid=" + p.applicationInfo.uid
1013 + " killAfterRestore="
1014 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001015 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001016 }
1017 }
1018
Dan Egnorefe52642009-06-24 00:16:33 -07001019 for (PackageInfo pkg : targetPkgs) {
1020 if (packageName == null || pkg.packageName.equals(packageName)) {
1021 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001022 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001023 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001024 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001025 mBackupParticipants.put(uid, set);
1026 }
Dan Egnorefe52642009-06-24 00:16:33 -07001027 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001028
1029 // If we've never seen this app before, schedule a backup for it
1030 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001031 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001032 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001033 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001034 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001035 }
Christopher Tate487529a2009-04-29 14:03:25 -07001036 }
1037 }
1038
Christopher Tate6785dd82009-06-18 15:58:25 -07001039 // Remove the given package's entry from our known active set. If
1040 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001041 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001042 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001043 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001044 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001045 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001046 } else {
1047 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001048 List<PackageInfo> knownPackages = allAgentPackages();
1049 for (PackageInfo pkg : knownPackages) {
1050 allApps.add(pkg.packageName);
1051 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001052 }
1053 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001054 }
1055
Joe Onorato8ad02812009-05-13 01:41:44 -04001056 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001057 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001058 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001059 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001060 + ") removing " + allPackageNames.size() + " entries");
1061 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001062 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001063 }
1064 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001065 for (String pkg : allPackageNames) {
1066 if (packageName == null || pkg.equals(packageName)) {
1067 int uid = -1;
1068 try {
1069 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1070 uid = info.applicationInfo.uid;
1071 } catch (NameNotFoundException e) {
1072 // we don't know this package name, so just skip it for now
1073 continue;
1074 }
1075
Christopher Tate181fafa2009-05-14 11:12:14 -07001076 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001077 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001078 // Find the existing entry with the same package name, and remove it.
1079 // We can't just remove(app) because the instances are different.
1080 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001081 if (entry.packageName.equals(pkg)) {
1082 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001083 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001084 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001085 break;
1086 }
1087 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001088 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001089 mBackupParticipants.delete(uid);
1090 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001091 }
1092 }
1093 }
1094 }
1095
Christopher Tate181fafa2009-05-14 11:12:14 -07001096 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001097 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001098 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001099 int flags = PackageManager.GET_SIGNATURES;
1100 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1101 int N = packages.size();
1102 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001103 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001104 try {
1105 ApplicationInfo app = pkg.applicationInfo;
1106 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001107 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001108 packages.remove(a);
1109 }
1110 else {
1111 // we will need the shared library path, so look that up and store it here
1112 app = mPackageManager.getApplicationInfo(pkg.packageName,
1113 PackageManager.GET_SHARED_LIBRARY_FILES);
1114 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1115 }
1116 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001117 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001118 }
1119 }
Dan Egnorefe52642009-06-24 00:16:33 -07001120 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001121 }
Christopher Tateaa088442009-06-16 18:25:46 -07001122
Christopher Tate3799bc22009-05-06 16:13:56 -07001123 // Reset the given package's known backup participants. Unlike add/remove, the update
1124 // action cannot be passed a null package name.
1125 void updatePackageParticipantsLocked(String packageName) {
1126 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001127 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001128 return;
1129 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001130 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001131
1132 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001133 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001134 List<String> allAppNames = new ArrayList<String>();
1135 for (PackageInfo pkg : allApps) {
1136 allAppNames.add(pkg.packageName);
1137 }
1138 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001139 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001140 }
1141
Christopher Tate84725812010-02-04 15:52:40 -08001142 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001143 // backed up at least once
1144 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001145 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1146
1147 synchronized (mEverStoredApps) {
1148 if (!mEverStoredApps.add(packageName)) return;
1149
1150 RandomAccessFile out = null;
1151 try {
1152 out = new RandomAccessFile(mEverStored, "rws");
1153 out.seek(out.length());
1154 out.writeUTF(packageName);
1155 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001156 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001157 } finally {
1158 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001159 }
1160 }
1161 }
1162
Christopher Tatee97e8072009-07-15 16:45:50 -07001163 // Remove our awareness of having ever backed up the given package
1164 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001165 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001166
Dan Egnor852f8e42009-09-30 11:20:45 -07001167 synchronized (mEverStoredApps) {
1168 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1169 // we'll recognize on initialization time that the package no longer
1170 // exists and fix it up then.
1171 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1172 RandomAccessFile known = null;
1173 try {
1174 known = new RandomAccessFile(tempKnownFile, "rws");
1175 mEverStoredApps.remove(packageName);
1176 for (String s : mEverStoredApps) {
1177 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001178 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001179 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001180 known.close();
1181 known = null;
1182 if (!tempKnownFile.renameTo(mEverStored)) {
1183 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1184 }
1185 } catch (IOException e) {
1186 // Bad: we couldn't create the new copy. For safety's sake we
1187 // abandon the whole process and remove all what's-backed-up
1188 // state entirely, meaning we'll force a backup pass for every
1189 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001190 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001191 mEverStoredApps.clear();
1192 tempKnownFile.delete();
1193 mEverStored.delete();
1194 } finally {
1195 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001196 }
1197 }
1198 }
1199
Christopher Tateb49ceb32010-02-08 16:22:24 -08001200 // Persistently record the current and ancestral backup tokens as well
1201 // as the set of packages with data [supposedly] available in the
1202 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001203 void writeRestoreTokens() {
1204 try {
1205 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001206
1207 // First, the version number of this record, for futureproofing
1208 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1209
1210 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001211 af.writeLong(mAncestralToken);
1212 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001213
1214 // Now write the set of ancestral packages
1215 if (mAncestralPackages == null) {
1216 af.writeInt(-1);
1217 } else {
1218 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001219 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001220 for (String pkgName : mAncestralPackages) {
1221 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001222 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001223 }
1224 }
Christopher Tate84725812010-02-04 15:52:40 -08001225 af.close();
1226 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001227 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001228 }
1229 }
1230
Dan Egnor87a02bc2009-06-17 02:30:10 -07001231 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001232 private IBackupTransport getTransport(String transportName) {
1233 synchronized (mTransports) {
1234 IBackupTransport transport = mTransports.get(transportName);
1235 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001237 }
1238 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001239 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001240 }
1241
Christopher Tatedf01dea2009-06-09 20:45:02 -07001242 // fire off a backup agent, blocking until it attaches or times out
1243 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1244 IBackupAgent agent = null;
1245 synchronized(mAgentConnectLock) {
1246 mConnecting = true;
1247 mConnectedAgent = null;
1248 try {
1249 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001250 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001251
1252 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001253 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001254 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1255 while (mConnecting && mConnectedAgent == null
1256 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001257 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001258 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001259 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001260 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001261 return null;
1262 }
1263 }
1264
1265 // if we timed out with no connect, abort and move on
1266 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001267 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001268 return null;
1269 }
1270 agent = mConnectedAgent;
1271 }
1272 } catch (RemoteException e) {
1273 // can't happen
1274 }
1275 }
1276 return agent;
1277 }
1278
Christopher Tatec7b31e32009-06-10 15:49:30 -07001279 // clear an application's data, blocking until the operation completes or times out
1280 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001281 // Don't wipe packages marked allowClearUserData=false
1282 try {
1283 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1284 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001285 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001286 + packageName);
1287 return;
1288 }
1289 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001290 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001291 return;
1292 }
1293
Christopher Tatec7b31e32009-06-10 15:49:30 -07001294 ClearDataObserver observer = new ClearDataObserver();
1295
1296 synchronized(mClearDataLock) {
1297 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001298 try {
1299 mActivityManager.clearApplicationUserData(packageName, observer);
1300 } catch (RemoteException e) {
1301 // can't happen because the activity manager is in this process
1302 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001303
1304 // only wait 10 seconds for the clear data to happen
1305 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1306 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1307 try {
1308 mClearDataLock.wait(5000);
1309 } catch (InterruptedException e) {
1310 // won't happen, but still.
1311 mClearingData = false;
1312 }
1313 }
1314 }
1315 }
1316
1317 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001318 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001319 synchronized(mClearDataLock) {
1320 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001321 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001322 }
1323 }
1324 }
1325
Christopher Tate1bb69062010-02-19 17:02:12 -08001326 // Get the restore-set token for the best-available restore set for this package:
1327 // the active set if possible, else the ancestral one. Returns zero if none available.
1328 long getAvailableRestoreToken(String packageName) {
1329 long token = mAncestralToken;
1330 synchronized (mQueueLock) {
1331 if (mEverStoredApps.contains(packageName)) {
1332 token = mCurrentToken;
1333 }
1334 }
1335 return token;
1336 }
1337
Christopher Tate44a27902010-01-27 17:15:49 -08001338 // -----
1339 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1340 boolean waitUntilOperationComplete(int token) {
1341 int finalState = OP_PENDING;
1342 synchronized (mCurrentOpLock) {
1343 try {
1344 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1345 try {
1346 mCurrentOpLock.wait();
1347 } catch (InterruptedException e) {}
1348 }
1349 } catch (IndexOutOfBoundsException e) {
1350 // the operation has been mysteriously cleared from our
1351 // bookkeeping -- consider this a success and ignore it.
1352 }
1353 }
1354 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001355 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001356 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001357 return finalState == OP_ACKNOWLEDGED;
1358 }
1359
1360 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001361 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001362 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001363 synchronized (mCurrentOpLock) {
1364 mCurrentOperations.put(token, OP_PENDING);
1365 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1366 mBackupHandler.sendMessageDelayed(msg, interval);
1367 }
Christopher Tate44a27902010-01-27 17:15:49 -08001368 }
1369
Christopher Tate043dadc2009-06-02 16:11:00 -07001370 // ----- Back up a set of applications via a worker thread -----
1371
Christopher Tate44a27902010-01-27 17:15:49 -08001372 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001373 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001374 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001375 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001376 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001377 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001378
Christopher Tate44a27902010-01-27 17:15:49 -08001379 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001380 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001381 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001382 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001383 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001384
1385 try {
1386 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1387 } catch (RemoteException e) {
1388 // can't happen; the transport is local
1389 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001390 }
1391
Christopher Tate043dadc2009-06-02 16:11:00 -07001392 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001393 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001394 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001395 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001396
Christopher Tate79588342009-06-30 16:11:49 -07001397 // Backups run at background priority
1398 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1399
Christopher Tate043dadc2009-06-02 16:11:00 -07001400 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001401 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001402
Dan Egnor852f8e42009-09-30 11:20:45 -07001403 // If we haven't stored package manager metadata yet, we must init the transport.
1404 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1405 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001406 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001407 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001408 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001409 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001410 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001411 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001412 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001413 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001414 }
Dan Egnor01445162009-09-21 17:04:05 -07001415 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001416
1417 // The package manager doesn't have a proper <application> etc, but since
1418 // it's running here in the system process we can just set up its agent
1419 // directly and use a synthetic BackupRequest. We always run this pass
1420 // because it's cheap and this way we guarantee that we don't get out of
1421 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001422 if (status == BackupConstants.TRANSPORT_OK) {
1423 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1424 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001425 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001426 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1427 status = processOneBackup(pmRequest,
1428 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1429 }
Christopher Tate90967f42009-09-20 15:28:33 -07001430
Dan Egnor01445162009-09-21 17:04:05 -07001431 if (status == BackupConstants.TRANSPORT_OK) {
1432 // Now run all the backups in our queue
1433 status = doQueuedBackups(mTransport);
1434 }
1435
1436 if (status == BackupConstants.TRANSPORT_OK) {
1437 // Tell the transport to finish everything it has buffered
1438 status = mTransport.finishBackup();
1439 if (status == BackupConstants.TRANSPORT_OK) {
1440 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001442 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001444 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001445 }
1446 }
1447
Dan Egnor01445162009-09-21 17:04:05 -07001448 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001449 // The backend reports that our dataset has been wiped. We need to
1450 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001451 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001453 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001454 }
1455 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001456 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001457 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001458 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001459 // If everything actually went through and this is the first time we've
1460 // done a backup, we can now record what the current backup dataset token
1461 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001462 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001463 try {
1464 mCurrentToken = mTransport.getCurrentRestoreSet();
1465 } catch (RemoteException e) { /* cannot happen */ }
1466 writeRestoreTokens();
1467 }
1468
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001469 // If things went wrong, we need to re-stage the apps we had expected
1470 // to be backing up in this pass. This journals the package names in
1471 // the current active pending-backup file, not in the we are holding
1472 // here in mJournal.
1473 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001474 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001475 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001476 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001477 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001478
1479 // We also want to reset the backup schedule based on whatever
1480 // the transport suggests by way of retry/backoff time.
1481 try {
1482 startBackupAlarmsLocked(mTransport.requestBackupTime());
1483 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001484 }
1485
1486 // Either backup was successful, in which case we of course do not need
1487 // this pass's journal any more; or it failed, in which case we just
1488 // re-enqueued all of these packages in the current active journal.
1489 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001490 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001492 }
1493
Christopher Tatec2af5d32010-02-02 15:18:58 -08001494 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001495 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001496 backupNow();
1497 }
1498
Dan Egnorbb9001c2009-07-27 12:20:13 -07001499 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001500 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001501 }
1502
Dan Egnor01445162009-09-21 17:04:05 -07001503 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001504 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001506
Christopher Tatec28083a2010-12-14 16:16:44 -08001507 // Verify that the requested app exists; it might be something that
1508 // requested a backup but was then uninstalled. The request was
1509 // journalled and rather than tamper with the journal it's safer
1510 // to sanity-check here.
1511 try {
1512 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1513 } catch (NameNotFoundException e) {
1514 Slog.d(TAG, "Package does not exist; skipping");
1515 continue;
1516 }
1517
Christopher Tate043dadc2009-06-02 16:11:00 -07001518 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001519 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001520 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001521 agent = bindToAgentSynchronous(request.appInfo,
1522 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001523 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001524 int result = processOneBackup(request, agent, transport);
1525 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001526 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001527 } catch (SecurityException ex) {
1528 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001530 } finally {
1531 try { // unbind even on timeout, just in case
1532 mActivityManager.unbindBackupAgent(request.appInfo);
1533 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001534 }
1535 }
Dan Egnor01445162009-09-21 17:04:05 -07001536
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001537 mWakelock.setWorkSource(null);
1538
Dan Egnor01445162009-09-21 17:04:05 -07001539 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001540 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001541
Dan Egnor01445162009-09-21 17:04:05 -07001542 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1543 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001544 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001546
Dan Egnorbb9001c2009-07-27 12:20:13 -07001547 File savedStateName = new File(mStateDir, packageName);
1548 File backupDataName = new File(mDataDir, packageName + ".data");
1549 File newStateName = new File(mStateDir, packageName + ".new");
1550
1551 ParcelFileDescriptor savedState = null;
1552 ParcelFileDescriptor backupData = null;
1553 ParcelFileDescriptor newState = null;
1554
1555 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001556 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001557 try {
1558 // Look up the package info & signatures. This is first so that if it
1559 // throws an exception, there's no file setup yet that would need to
1560 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001561 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1562 // The metadata 'package' is synthetic
1563 packInfo = new PackageInfo();
1564 packInfo.packageName = packageName;
1565 } else {
1566 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001567 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001568 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001569
Christopher Tatec7b31e32009-06-10 15:49:30 -07001570 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001571 // the saved-state "file". This is by definition an incremental,
1572 // so we build a saved state file to pass.
1573 savedState = ParcelFileDescriptor.open(savedStateName,
1574 ParcelFileDescriptor.MODE_READ_ONLY |
1575 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001576
Dan Egnorbb9001c2009-07-27 12:20:13 -07001577 backupData = ParcelFileDescriptor.open(backupDataName,
1578 ParcelFileDescriptor.MODE_READ_WRITE |
1579 ParcelFileDescriptor.MODE_CREATE |
1580 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001581
Dan Egnorbb9001c2009-07-27 12:20:13 -07001582 newState = ParcelFileDescriptor.open(newStateName,
1583 ParcelFileDescriptor.MODE_READ_WRITE |
1584 ParcelFileDescriptor.MODE_CREATE |
1585 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001586
Christopher Tate44a27902010-01-27 17:15:49 -08001587 // Initiate the target's backup pass
1588 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate4a627c72011-04-01 14:43:32 -07001589 agent.doBackup(savedState, backupData, newState, false,
1590 token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001591 boolean success = waitUntilOperationComplete(token);
1592
1593 if (!success) {
1594 // timeout -- bail out into the failed-transaction logic
1595 throw new RuntimeException("Backup timeout");
1596 }
1597
Dan Egnorbb9001c2009-07-27 12:20:13 -07001598 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001599 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001600 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001602 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001603 backupDataName.delete();
1604 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001605 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 } finally {
1607 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1608 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1609 try { if (newState != null) newState.close(); } catch (IOException e) {}
1610 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001611 synchronized (mCurrentOpLock) {
1612 mCurrentOperations.clear();
1613 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614 }
1615
1616 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001617 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001618 try {
1619 int size = (int) backupDataName.length();
1620 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001621 if (result == BackupConstants.TRANSPORT_OK) {
1622 backupData = ParcelFileDescriptor.open(backupDataName,
1623 ParcelFileDescriptor.MODE_READ_ONLY);
1624 result = transport.performBackup(packInfo, backupData);
1625 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001626
Dan Egnor83861e72009-09-17 16:17:55 -07001627 // TODO - We call finishBackup() for each application backed up, because
1628 // we need to know now whether it succeeded or failed. Instead, we should
1629 // hold off on finishBackup() until the end, which implies holding off on
1630 // renaming *all* the output state files (see below) until that happens.
1631
Dan Egnor01445162009-09-21 17:04:05 -07001632 if (result == BackupConstants.TRANSPORT_OK) {
1633 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001634 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001637 }
1638
1639 // After successful transport, delete the now-stale data
1640 // and juggle the files so that next time we supply the agent
1641 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001642 if (result == BackupConstants.TRANSPORT_OK) {
1643 backupDataName.delete();
1644 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001645 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001646 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001647 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001648 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001649 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001651 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001652 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001653 } finally {
1654 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001655 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001656
Dan Egnor01445162009-09-21 17:04:05 -07001657 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001658 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001659 }
1660
Christopher Tatedf01dea2009-06-09 20:45:02 -07001661
Christopher Tate4a627c72011-04-01 14:43:32 -07001662 // ----- Full backup to a file/socket -----
1663
1664 class PerformFullBackupTask implements Runnable {
1665 ParcelFileDescriptor mOutputFile;
1666 IFullBackupRestoreObserver mObserver;
1667 boolean mIncludeApks;
1668 boolean mIncludeShared;
1669 boolean mAllApps;
1670 String[] mPackages;
1671 AtomicBoolean mLatchObject;
1672 File mFilesDir;
1673 File mManifestFile;
1674
1675 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1676 boolean includeApks, boolean includeShared,
1677 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1678 mOutputFile = fd;
1679 mObserver = observer;
1680 mIncludeApks = includeApks;
1681 mIncludeShared = includeShared;
1682 mAllApps = doAllApps;
1683 mPackages = packages;
1684 mLatchObject = latch;
1685
1686 mFilesDir = new File("/data/system");
1687 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1688 }
1689
1690 @Override
1691 public void run() {
1692 final List<PackageInfo> packagesToBackup;
1693
Christopher Tate75a99702011-05-18 16:28:19 -07001694 Slog.i(TAG, "--- Performing full-dataset restore ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07001695 sendStartBackup();
1696
1697 // doAllApps supersedes the package set if any
1698 if (mAllApps) {
1699 packagesToBackup = mPackageManager.getInstalledPackages(
1700 PackageManager.GET_SIGNATURES);
1701 } else {
1702 packagesToBackup = new ArrayList<PackageInfo>();
1703 for (String pkgName : mPackages) {
1704 try {
1705 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1706 PackageManager.GET_SIGNATURES));
1707 } catch (NameNotFoundException e) {
1708 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1709 }
1710 }
1711 }
1712
Christopher Tatea858cb02011-06-03 12:27:51 -07001713 // Cull any packages that have indicated that backups are not permitted.
1714 for (int i = 0; i < packagesToBackup.size(); ) {
1715 PackageInfo info = packagesToBackup.get(i);
1716 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
1717 packagesToBackup.remove(i);
1718 } else {
1719 i++;
1720 }
1721 }
1722
Christopher Tate4a627c72011-04-01 14:43:32 -07001723 // Now back up the app data via the agent mechanism
1724 PackageInfo pkg = null;
1725 try {
1726 int N = packagesToBackup.size();
1727 for (int i = 0; i < N; i++) {
1728 pkg = packagesToBackup.get(i);
1729
1730 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1731
1732 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1733 IApplicationThread.BACKUP_MODE_FULL);
1734 if (agent != null) {
1735 try {
Christopher Tatedc92c822011-05-13 15:38:02 -07001736 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001737 boolean sendApk = mIncludeApks
1738 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1739 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1740 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1741
1742 sendOnBackupPackage(pkg.packageName);
1743
1744 {
1745 BackupDataOutput output = new BackupDataOutput(
1746 mOutputFile.getFileDescriptor());
1747
1748 if (DEBUG) Slog.d(TAG, "Writing manifest for " + pkg.packageName);
1749 writeAppManifest(pkg, mManifestFile, sendApk);
1750 FullBackup.backupToTar(pkg.packageName, null, null,
1751 mFilesDir.getAbsolutePath(),
1752 mManifestFile.getAbsolutePath(),
1753 output);
1754 }
1755
1756 if (DEBUG) Slog.d(TAG, "Calling doBackup()");
1757 final int token = generateToken();
1758 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL);
1759 agent.doBackup(null, mOutputFile, null, sendApk,
1760 token, mBackupManagerBinder);
1761 boolean success = waitUntilOperationComplete(token);
1762 if (!success) {
1763 Slog.d(TAG, "Full backup failed on package " + pkg.packageName);
1764 } else {
1765 if (DEBUG) Slog.d(TAG, "Full backup success: " + pkg.packageName);
1766 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001767 } catch (IOException e) {
1768 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
1769 }
1770 } else {
1771 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1772 }
1773 tearDown(pkg);
1774 }
1775 } catch (RemoteException e) {
1776 Slog.e(TAG, "App died during full backup");
1777 } finally {
1778 if (pkg != null) {
1779 tearDown(pkg);
1780 }
1781 try {
1782 mOutputFile.close();
1783 } catch (IOException e) {
1784 /* nothing we can do about this */
1785 }
1786 synchronized (mCurrentOpLock) {
1787 mCurrentOperations.clear();
1788 }
1789 synchronized (mLatchObject) {
1790 mLatchObject.set(true);
1791 mLatchObject.notifyAll();
1792 }
1793 sendEndBackup();
1794 mWakelock.release();
1795 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1796 }
1797 }
1798
1799 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1800 throws IOException {
1801 // Manifest format. All data are strings ending in LF:
1802 // BACKUP_MANIFEST_VERSION, currently 1
1803 //
1804 // Version 1:
1805 // package name
1806 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07001807 // platform versionCode
1808 // getInstallerPackageName() for this package (maybe empty)
1809 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07001810 // number of signatures == N
1811 // N*: signature byte array in ascii format per Signature.toCharsString()
1812 StringBuilder builder = new StringBuilder(4096);
1813 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
1814
1815 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
1816 printer.println(pkg.packageName);
1817 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07001818 printer.println(Integer.toString(Build.VERSION.SDK_INT));
1819
1820 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
1821 printer.println((installerName != null) ? installerName : "");
1822
Christopher Tate4a627c72011-04-01 14:43:32 -07001823 printer.println(withApk ? "1" : "0");
1824 if (pkg.signatures == null) {
1825 printer.println("0");
1826 } else {
1827 printer.println(Integer.toString(pkg.signatures.length));
1828 for (Signature sig : pkg.signatures) {
1829 printer.println(sig.toCharsString());
1830 }
1831 }
1832
1833 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07001834 outstream.write(builder.toString().getBytes());
1835 outstream.close();
1836 }
1837
1838 private void tearDown(PackageInfo pkg) {
1839 final ApplicationInfo app = pkg.applicationInfo;
1840 try {
1841 // unbind and tidy up even on timeout or failure, just in case
1842 mActivityManager.unbindBackupAgent(app);
1843
Christopher Tatedc92c822011-05-13 15:38:02 -07001844 // The agent was running with a stub Application object, so shut it down.
1845 // !!! We hardcode the confirmation UI's package name here rather than use a
1846 // manifest flag! TODO something less direct.
1847 if (app.uid != Process.SYSTEM_UID
1848 && !pkg.packageName.equals("com.android.backupconfirm")) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001849 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
1850 mActivityManager.killApplicationProcess(app.processName, app.uid);
1851 } else {
1852 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
1853 }
1854 } catch (RemoteException e) {
1855 Slog.d(TAG, "Lost app trying to shut down");
1856 }
1857 }
1858
1859 // wrappers for observer use
1860 void sendStartBackup() {
1861 if (mObserver != null) {
1862 try {
1863 mObserver.onStartBackup();
1864 } catch (RemoteException e) {
1865 Slog.w(TAG, "full backup observer went away: startBackup");
1866 mObserver = null;
1867 }
1868 }
1869 }
1870
1871 void sendOnBackupPackage(String name) {
1872 if (mObserver != null) {
1873 try {
1874 // TODO: use a more user-friendly name string
1875 mObserver.onBackupPackage(name);
1876 } catch (RemoteException e) {
1877 Slog.w(TAG, "full backup observer went away: backupPackage");
1878 mObserver = null;
1879 }
1880 }
1881 }
1882
1883 void sendEndBackup() {
1884 if (mObserver != null) {
1885 try {
1886 mObserver.onEndBackup();
1887 } catch (RemoteException e) {
1888 Slog.w(TAG, "full backup observer went away: endBackup");
1889 mObserver = null;
1890 }
1891 }
1892 }
1893 }
1894
1895
Christopher Tate75a99702011-05-18 16:28:19 -07001896 // ----- Full restore from a file/socket -----
1897
1898 // Description of a file in the restore datastream
1899 static class FileMetadata {
1900 String packageName; // name of the owning app
1901 String installerPackageName; // name of the market-type app that installed the owner
1902 int type; // e.g. FullBackup.TYPE_DIRECTORY
1903 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
1904 String path; // subpath within the semantic domain
1905 long mode; // e.g. 0666 (actually int)
1906 long mtime; // last mod time, UTC time_t (actually int)
1907 long size; // bytes of content
1908 }
1909
1910 enum RestorePolicy {
1911 IGNORE,
1912 ACCEPT,
1913 ACCEPT_IF_APK
1914 }
1915
1916 class PerformFullRestoreTask implements Runnable {
1917 ParcelFileDescriptor mInputFile;
1918 IFullBackupRestoreObserver mObserver;
1919 AtomicBoolean mLatchObject;
1920 IBackupAgent mAgent;
1921 String mAgentPackage;
1922 ApplicationInfo mTargetApp;
1923 ParcelFileDescriptor[] mPipes = null;
1924
1925 // possible handling states for a given package in the restore dataset
1926 final HashMap<String, RestorePolicy> mPackagePolicies
1927 = new HashMap<String, RestorePolicy>();
1928
1929 // installer package names for each encountered app, derived from the manifests
1930 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
1931
1932 // Signatures for a given package found in its manifest file
1933 final HashMap<String, Signature[]> mManifestSignatures
1934 = new HashMap<String, Signature[]>();
1935
1936 // Packages we've already wiped data on when restoring their first file
1937 final HashSet<String> mClearedPackages = new HashSet<String>();
1938
1939 PerformFullRestoreTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1940 AtomicBoolean latch) {
1941 mInputFile = fd;
1942 mObserver = observer;
1943 mLatchObject = latch;
1944 mAgent = null;
1945 mAgentPackage = null;
1946 mTargetApp = null;
1947
1948 // Which packages we've already wiped data on. We prepopulate this
1949 // with a whitelist of packages known to be unclearable.
1950 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07001951 mClearedPackages.add("com.android.providers.settings");
1952 }
1953
1954 class RestoreFileRunnable implements Runnable {
1955 IBackupAgent mAgent;
1956 FileMetadata mInfo;
1957 ParcelFileDescriptor mSocket;
1958 int mToken;
1959
1960 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
1961 ParcelFileDescriptor socket, int token) throws IOException {
1962 mAgent = agent;
1963 mInfo = info;
1964 mToken = token;
1965
1966 // This class is used strictly for process-local binder invocations. The
1967 // semantics of ParcelFileDescriptor differ in this case; in particular, we
1968 // do not automatically get a 'dup'ed descriptor that we can can continue
1969 // to use asynchronously from the caller. So, we make sure to dup it ourselves
1970 // before proceeding to do the restore.
1971 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1972 }
1973
1974 @Override
1975 public void run() {
1976 try {
1977 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
1978 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
1979 mToken, mBackupManagerBinder);
1980 } catch (RemoteException e) {
1981 // never happens; this is used strictly for local binder calls
1982 }
1983 }
1984 }
1985
1986 @Override
1987 public void run() {
1988 Slog.i(TAG, "--- Performing full-dataset restore ---");
1989 sendStartRestore();
1990
1991 try {
1992 byte[] buffer = new byte[32 * 1024];
1993 FileInputStream instream = new FileInputStream(mInputFile.getFileDescriptor());
1994
1995 boolean didRestore;
1996 do {
1997 didRestore = restoreOneFile(instream, buffer);
1998 } while (didRestore);
1999
2000 if (DEBUG) Slog.v(TAG, "Done consuming input tarfile");
2001 } finally {
2002 tearDownPipes();
2003 tearDownAgent(mTargetApp);
2004
2005 try {
2006 mInputFile.close();
2007 } catch (IOException e) {
2008 /* nothing we can do about this */
2009 }
2010 synchronized (mCurrentOpLock) {
2011 mCurrentOperations.clear();
2012 }
2013 synchronized (mLatchObject) {
2014 mLatchObject.set(true);
2015 mLatchObject.notifyAll();
2016 }
2017 sendEndRestore();
2018 mWakelock.release();
2019 if (DEBUG) Slog.d(TAG, "Full restore pass complete.");
2020 }
2021 }
2022
2023 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2024 FileMetadata info;
2025 try {
2026 info = readTarHeaders(instream);
2027 if (info != null) {
2028 if (DEBUG) {
2029 dumpFileMetadata(info);
2030 }
2031
2032 final String pkg = info.packageName;
2033 if (!pkg.equals(mAgentPackage)) {
2034 // okay, change in package; set up our various
2035 // bookkeeping if we haven't seen it yet
2036 if (!mPackagePolicies.containsKey(pkg)) {
2037 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2038 }
2039
2040 // Clean up the previous agent relationship if necessary,
2041 // and let the observer know we're considering a new app.
2042 if (mAgent != null) {
2043 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2044 tearDownPipes();
2045 tearDownAgent(mTargetApp);
2046 mTargetApp = null;
2047 mAgentPackage = null;
2048 }
2049 }
2050
2051 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2052 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2053 mPackageInstallers.put(pkg, info.installerPackageName);
2054 // We've read only the manifest content itself at this point,
2055 // so consume the footer before looping around to the next
2056 // input file
2057 skipTarPadding(info.size, instream);
2058 sendOnRestorePackage(pkg);
2059 } else {
2060 // Non-manifest, so it's actual file data. Is this a package
2061 // we're ignoring?
2062 boolean okay = true;
2063 RestorePolicy policy = mPackagePolicies.get(pkg);
2064 switch (policy) {
2065 case IGNORE:
2066 okay = false;
2067 break;
2068
2069 case ACCEPT_IF_APK:
2070 // If we're in accept-if-apk state, then the first file we
2071 // see MUST be the apk.
2072 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2073 if (DEBUG) Slog.d(TAG, "APK file; installing");
2074 // Try to install the app.
2075 String installerName = mPackageInstallers.get(pkg);
2076 okay = installApk(info, installerName, instream);
2077 // good to go; promote to ACCEPT
2078 mPackagePolicies.put(pkg, (okay)
2079 ? RestorePolicy.ACCEPT
2080 : RestorePolicy.IGNORE);
2081 // At this point we've consumed this file entry
2082 // ourselves, so just strip the tar footer and
2083 // go on to the next file in the input stream
2084 skipTarPadding(info.size, instream);
2085 return true;
2086 } else {
2087 // File data before (or without) the apk. We can't
2088 // handle it coherently in this case so ignore it.
2089 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2090 okay = false;
2091 }
2092 break;
2093
2094 case ACCEPT:
2095 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2096 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2097 // we can take the data without the apk, so we
2098 // *want* to do so. skip the apk by declaring this
2099 // one file not-okay without changing the restore
2100 // policy for the package.
2101 okay = false;
2102 }
2103 break;
2104
2105 default:
2106 // Something has gone dreadfully wrong when determining
2107 // the restore policy from the manifest. Ignore the
2108 // rest of this package's data.
2109 Slog.e(TAG, "Invalid policy from manifest");
2110 okay = false;
2111 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2112 break;
2113 }
2114
2115 // If the policy is satisfied, go ahead and set up to pipe the
2116 // data to the agent.
2117 if (DEBUG && okay && mAgent != null) {
2118 Slog.i(TAG, "Reusing existing agent instance");
2119 }
2120 if (okay && mAgent == null) {
2121 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2122
2123 try {
2124 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2125
2126 // If we haven't sent any data to this app yet, we probably
2127 // need to clear it first. Check that.
2128 if (!mClearedPackages.contains(pkg)) {
2129 // apps with their own full backup agents are
2130 // responsible for coherently managing a full
2131 // restore.
2132 if (mTargetApp.fullBackupAgentName == null) {
2133 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2134 clearApplicationDataSynchronous(pkg);
2135 } else {
2136 if (DEBUG) Slog.d(TAG, "full backup agent ("
2137 + mTargetApp.fullBackupAgentName + ") => no clear");
2138 }
2139 mClearedPackages.add(pkg);
2140 } else {
2141 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2142 }
2143
2144 // All set; now set up the IPC and launch the agent
2145 setUpPipes();
2146 mAgent = bindToAgentSynchronous(mTargetApp,
2147 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2148 mAgentPackage = pkg;
2149 } catch (IOException e) {
2150 // fall through to error handling
2151 } catch (NameNotFoundException e) {
2152 // fall through to error handling
2153 }
2154
2155 if (mAgent == null) {
2156 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2157 okay = false;
2158 tearDownPipes();
2159 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2160 }
2161 }
2162
2163 // Sanity check: make sure we never give data to the wrong app. This
2164 // should never happen but a little paranoia here won't go amiss.
2165 if (okay && !pkg.equals(mAgentPackage)) {
2166 Slog.e(TAG, "Restoring data for " + pkg
2167 + " but agent is for " + mAgentPackage);
2168 okay = false;
2169 }
2170
2171 // At this point we have an agent ready to handle the full
2172 // restore data as well as a pipe for sending data to
2173 // that agent. Tell the agent to start reading from the
2174 // pipe.
2175 if (okay) {
2176 boolean agentSuccess = true;
2177 long toCopy = info.size;
2178 final int token = generateToken();
2179 try {
2180 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2181 + info.path);
2182 prepareOperationTimeout(token,
2183 TIMEOUT_FULL_BACKUP_INTERVAL);
2184 // fire up the app's agent listening on the socket. If
2185 // the agent is running in the system process we can't
2186 // just invoke it asynchronously, so we provide a thread
2187 // for it here.
2188 if (mTargetApp.processName.equals("system")) {
2189 Slog.d(TAG, "system process agent - spinning a thread");
2190 RestoreFileRunnable runner = new RestoreFileRunnable(
2191 mAgent, info, mPipes[0], token);
2192 new Thread(runner).start();
2193 } else {
2194 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2195 info.domain, info.path, info.mode, info.mtime,
2196 token, mBackupManagerBinder);
2197 }
2198 } catch (IOException e) {
2199 // couldn't dup the socket for a process-local restore
2200 Slog.d(TAG, "Couldn't establish restore");
2201 agentSuccess = false;
2202 okay = false;
2203 } catch (RemoteException e) {
2204 // whoops, remote agent went away. We'll eat the content
2205 // ourselves, then, and not copy it over.
2206 Slog.e(TAG, "Agent crashed during full restore");
2207 agentSuccess = false;
2208 okay = false;
2209 }
2210
2211 // Copy over the data if the agent is still good
2212 if (okay) {
2213 boolean pipeOkay = true;
2214 FileOutputStream pipe = new FileOutputStream(
2215 mPipes[1].getFileDescriptor());
2216 if (DEBUG) Slog.d(TAG, "Piping data to agent");
2217 while (toCopy > 0) {
2218 int toRead = (toCopy > buffer.length)
2219 ? buffer.length : (int)toCopy;
2220 int nRead = instream.read(buffer, 0, toRead);
2221 if (nRead <= 0) break;
2222 toCopy -= nRead;
2223
2224 // send it to the output pipe as long as things
2225 // are still good
2226 if (pipeOkay) {
2227 try {
2228 pipe.write(buffer, 0, nRead);
2229 } catch (IOException e) {
2230 Slog.e(TAG,
2231 "Failed to write to restore pipe", e);
2232 pipeOkay = false;
2233 }
2234 }
2235 }
2236
2237 // done sending that file! Now we just need to consume
2238 // the delta from info.size to the end of block.
2239 skipTarPadding(info.size, instream);
2240
2241 // and now that we've sent it all, wait for the remote
2242 // side to acknowledge receipt
2243 agentSuccess = waitUntilOperationComplete(token);
2244 }
2245
2246 // okay, if the remote end failed at any point, deal with
2247 // it by ignoring the rest of the restore on it
2248 if (!agentSuccess) {
2249 mBackupHandler.removeMessages(MSG_TIMEOUT);
2250 tearDownPipes();
2251 tearDownAgent(mTargetApp);
2252 mAgent = null;
2253 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2254 }
2255 }
2256
2257 // Problems setting up the agent communication, or an already-
2258 // ignored package: skip to the next tar stream entry by
2259 // reading and discarding this file.
2260 if (!okay) {
2261 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2262 long bytesToConsume = (info.size + 511) & ~511;
2263 while (bytesToConsume > 0) {
2264 int toRead = (bytesToConsume > buffer.length)
2265 ? buffer.length : (int)bytesToConsume;
2266 long nRead = instream.read(buffer, 0, toRead);
2267 if (nRead <= 0) break;
2268 bytesToConsume -= nRead;
2269 }
2270 }
2271 }
2272 }
2273 } catch (IOException e) {
2274 Slog.w(TAG, "io exception on restore socket read", e);
2275 // treat as EOF
2276 info = null;
2277 }
2278
2279 return (info != null);
2280 }
2281
2282 void setUpPipes() throws IOException {
2283 mPipes = ParcelFileDescriptor.createPipe();
2284 }
2285
2286 void tearDownPipes() {
2287 if (mPipes != null) {
2288 if (mPipes[0] != null) {
2289 try {
2290 mPipes[0].close();
2291 mPipes[0] = null;
2292 mPipes[1].close();
2293 mPipes[1] = null;
2294 } catch (IOException e) {
2295 Slog.w(TAG, "Couldn't close agent pipes", e);
2296 }
2297 }
2298 mPipes = null;
2299 }
2300 }
2301
2302 void tearDownAgent(ApplicationInfo app) {
2303 if (mAgent != null) {
2304 try {
2305 // unbind and tidy up even on timeout or failure, just in case
2306 mActivityManager.unbindBackupAgent(app);
2307
2308 // The agent was running with a stub Application object, so shut it down.
2309 // !!! We hardcode the confirmation UI's package name here rather than use a
2310 // manifest flag! TODO something less direct.
2311 if (app.uid != Process.SYSTEM_UID
2312 && !app.packageName.equals("com.android.backupconfirm")) {
2313 if (DEBUG) Slog.d(TAG, "Killing host process");
2314 mActivityManager.killApplicationProcess(app.processName, app.uid);
2315 } else {
2316 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
2317 }
2318 } catch (RemoteException e) {
2319 Slog.d(TAG, "Lost app trying to shut down");
2320 }
2321 mAgent = null;
2322 }
2323 }
2324
2325 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
2326 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07002327 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002328 int mResult;
2329
2330 public void reset() {
2331 synchronized (mDone) {
2332 mDone.set(false);
2333 }
2334 }
2335
2336 public void waitForCompletion() {
2337 synchronized (mDone) {
2338 while (mDone.get() == false) {
2339 try {
2340 mDone.wait();
2341 } catch (InterruptedException e) { }
2342 }
2343 }
2344 }
2345
2346 int getResult() {
2347 return mResult;
2348 }
2349
2350 @Override
2351 public void packageInstalled(String packageName, int returnCode)
2352 throws RemoteException {
2353 synchronized (mDone) {
2354 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07002355 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002356 mDone.set(true);
2357 mDone.notifyAll();
2358 }
2359 }
2360 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002361
2362 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
2363 final AtomicBoolean mDone = new AtomicBoolean();
2364 int mResult;
2365
2366 public void reset() {
2367 synchronized (mDone) {
2368 mDone.set(false);
2369 }
2370 }
2371
2372 public void waitForCompletion() {
2373 synchronized (mDone) {
2374 while (mDone.get() == false) {
2375 try {
2376 mDone.wait();
2377 } catch (InterruptedException e) { }
2378 }
2379 }
2380 }
2381
2382 @Override
2383 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
2384 synchronized (mDone) {
2385 mResult = returnCode;
2386 mDone.set(true);
2387 mDone.notifyAll();
2388 }
2389 }
2390 }
2391
Christopher Tate75a99702011-05-18 16:28:19 -07002392 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07002393 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07002394
2395 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
2396 boolean okay = true;
2397
2398 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
2399
2400 // The file content is an .apk file. Copy it out to a staging location and
2401 // attempt to install it.
2402 File apkFile = new File(mDataDir, info.packageName);
2403 try {
2404 FileOutputStream apkStream = new FileOutputStream(apkFile);
2405 byte[] buffer = new byte[32 * 1024];
2406 long size = info.size;
2407 while (size > 0) {
2408 long toRead = (buffer.length < size) ? buffer.length : size;
2409 int didRead = instream.read(buffer, 0, (int)toRead);
2410 apkStream.write(buffer, 0, didRead);
2411 size -= didRead;
2412 }
2413 apkStream.close();
2414
2415 // make sure the installer can read it
2416 apkFile.setReadable(true, false);
2417
2418 // Now install it
2419 Uri packageUri = Uri.fromFile(apkFile);
2420 mInstallObserver.reset();
2421 mPackageManager.installPackage(packageUri, mInstallObserver,
2422 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
2423 mInstallObserver.waitForCompletion();
2424
2425 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
2426 // The only time we continue to accept install of data even if the
2427 // apk install failed is if we had already determined that we could
2428 // accept the data regardless.
2429 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
2430 okay = false;
2431 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002432 } else {
2433 // Okay, the install succeeded. Make sure it was the right app.
2434 boolean uninstall = false;
2435 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
2436 Slog.w(TAG, "Restore stream claimed to include apk for "
2437 + info.packageName + " but apk was really "
2438 + mInstallObserver.mPackageName);
2439 // delete the package we just put in place; it might be fraudulent
2440 okay = false;
2441 uninstall = true;
2442 } else {
2443 try {
2444 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
2445 PackageManager.GET_SIGNATURES);
2446 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2447 Slog.w(TAG, "Restore stream contains apk of package "
2448 + info.packageName + " but it disallows backup/restore");
2449 okay = false;
2450 } else {
2451 // So far so good -- do the signatures match the manifest?
2452 Signature[] sigs = mManifestSignatures.get(info.packageName);
2453 if (!signaturesMatch(sigs, pkg)) {
2454 Slog.w(TAG, "Installed app " + info.packageName
2455 + " signatures do not match restore manifest");
2456 okay = false;
2457 uninstall = true;
2458 }
2459 }
2460 } catch (NameNotFoundException e) {
2461 Slog.w(TAG, "Install of package " + info.packageName
2462 + " succeeded but now not found");
2463 okay = false;
2464 }
2465 }
2466
2467 // If we're not okay at this point, we need to delete the package
2468 // that we just installed.
2469 if (uninstall) {
2470 mDeleteObserver.reset();
2471 mPackageManager.deletePackage(mInstallObserver.mPackageName,
2472 mDeleteObserver, 0);
2473 mDeleteObserver.waitForCompletion();
2474 }
Christopher Tate75a99702011-05-18 16:28:19 -07002475 }
2476 } catch (IOException e) {
2477 Slog.e(TAG, "Unable to transcribe restored apk for install");
2478 okay = false;
2479 } finally {
2480 apkFile.delete();
2481 }
2482
2483 return okay;
2484 }
2485
2486 // Given an actual file content size, consume the post-content padding mandated
2487 // by the tar format.
2488 void skipTarPadding(long size, InputStream instream) throws IOException {
2489 long partial = (size + 512) % 512;
2490 if (partial > 0) {
2491 byte[] buffer = new byte[512];
2492 instream.read(buffer, 0, 512 - (int)partial);
2493 }
2494 }
2495
2496 // Returns a policy constant; takes a buffer arg to reduce memory churn
2497 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
2498 throws IOException {
2499 // Fail on suspiciously large manifest files
2500 if (info.size > 64 * 1024) {
2501 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
2502 }
2503 byte[] buffer = new byte[(int) info.size];
2504 int nRead = 0;
2505 while (nRead < info.size) {
2506 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
2507 }
2508
2509 RestorePolicy policy = RestorePolicy.IGNORE;
2510 String[] str = new String[1];
2511 int offset = 0;
2512
2513 try {
2514 offset = extractLine(buffer, offset, str);
2515 int version = Integer.parseInt(str[0]);
2516 if (version == BACKUP_MANIFEST_VERSION) {
2517 offset = extractLine(buffer, offset, str);
2518 String manifestPackage = str[0];
2519 // TODO: handle <original-package>
2520 if (manifestPackage.equals(info.packageName)) {
2521 offset = extractLine(buffer, offset, str);
2522 version = Integer.parseInt(str[0]); // app version
2523 offset = extractLine(buffer, offset, str);
2524 int platformVersion = Integer.parseInt(str[0]);
2525 offset = extractLine(buffer, offset, str);
2526 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
2527 offset = extractLine(buffer, offset, str);
2528 boolean hasApk = str[0].equals("1");
2529 offset = extractLine(buffer, offset, str);
2530 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07002531 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002532 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07002533 for (int i = 0; i < numSigs; i++) {
2534 offset = extractLine(buffer, offset, str);
2535 sigs[i] = new Signature(str[0]);
2536 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002537 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07002538
2539 // Okay, got the manifest info we need...
2540 try {
Christopher Tate75a99702011-05-18 16:28:19 -07002541 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2542 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07002543 // Fall through to IGNORE if the app explicitly disallows backup
2544 final int flags = pkgInfo.applicationInfo.flags;
2545 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
2546 // Verify signatures against any installed version; if they
2547 // don't match, then we fall though and ignore the data. The
2548 // signatureMatch() method explicitly ignores the signature
2549 // check for packages installed on the system partition, because
2550 // such packages are signed with the platform cert instead of
2551 // the app developer's cert, so they're different on every
2552 // device.
2553 if (signaturesMatch(sigs, pkgInfo)) {
2554 if (pkgInfo.versionCode >= version) {
2555 Slog.i(TAG, "Sig + version match; taking data");
2556 policy = RestorePolicy.ACCEPT;
2557 } else {
2558 // The data is from a newer version of the app than
2559 // is presently installed. That means we can only
2560 // use it if the matching apk is also supplied.
2561 Slog.d(TAG, "Data version " + version
2562 + " is newer than installed version "
2563 + pkgInfo.versionCode + " - requiring apk");
2564 policy = RestorePolicy.ACCEPT_IF_APK;
2565 }
Christopher Tate75a99702011-05-18 16:28:19 -07002566 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07002567 Slog.w(TAG, "Restore manifest signatures do not match "
2568 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07002569 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002570 } else {
2571 if (DEBUG) Slog.i(TAG, "Restore manifest from "
2572 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07002573 }
2574 } catch (NameNotFoundException e) {
2575 // Okay, the target app isn't installed. We can process
2576 // the restore properly only if the dataset provides the
2577 // apk file and we can successfully install it.
2578 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
2579 + " not installed; requiring apk in dataset");
2580 policy = RestorePolicy.ACCEPT_IF_APK;
2581 }
2582
2583 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
2584 Slog.i(TAG, "Cannot restore package " + info.packageName
2585 + " without the matching .apk");
2586 }
2587 } else {
2588 Slog.i(TAG, "Missing signature on backed-up package "
2589 + info.packageName);
2590 }
2591 } else {
2592 Slog.i(TAG, "Expected package " + info.packageName
2593 + " but restore manifest claims " + manifestPackage);
2594 }
2595 } else {
2596 Slog.i(TAG, "Unknown restore manifest version " + version
2597 + " for package " + info.packageName);
2598 }
2599 } catch (NumberFormatException e) {
2600 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
2601 }
2602
2603 return policy;
2604 }
2605
2606 // Builds a line from a byte buffer starting at 'offset', and returns
2607 // the index of the next unconsumed data in the buffer.
2608 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
2609 final int end = buffer.length;
2610 if (offset >= end) throw new IOException("Incomplete data");
2611
2612 int pos;
2613 for (pos = offset; pos < end; pos++) {
2614 byte c = buffer[pos];
2615 // at LF we declare end of line, and return the next char as the
2616 // starting point for the next time through
2617 if (c == '\n') {
2618 break;
2619 }
2620 }
2621 outStr[0] = new String(buffer, offset, pos - offset);
2622 pos++; // may be pointing an extra byte past the end but that's okay
2623 return pos;
2624 }
2625
2626 void dumpFileMetadata(FileMetadata info) {
2627 if (DEBUG) {
2628 StringBuilder b = new StringBuilder(128);
2629
2630 // mode string
2631 b.append((info.type == FullBackup.TYPE_DIRECTORY) ? 'd' : '-');
2632 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
2633 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
2634 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
2635 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
2636 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
2637 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
2638 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
2639 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
2640 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
2641 b.append(String.format(" %9d ", info.size));
2642
2643 Date stamp = new Date(info.mtime);
2644 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
2645
2646 b.append(info.packageName);
2647 b.append(" :: ");
2648 b.append(info.domain);
2649 b.append(" :: ");
2650 b.append(info.path);
2651
2652 Slog.i(TAG, b.toString());
2653 }
2654 }
2655 // Consume a tar file header block [sequence] and accumulate the relevant metadata
2656 FileMetadata readTarHeaders(InputStream instream) throws IOException {
2657 byte[] block = new byte[512];
2658 FileMetadata info = null;
2659
2660 boolean gotHeader = readTarHeader(instream, block);
2661 if (gotHeader) {
2662 // okay, presume we're okay, and extract the various metadata
2663 info = new FileMetadata();
2664 info.size = extractRadix(block, 124, 12, 8);
2665 info.mtime = extractRadix(block, 136, 12, 8);
2666 info.mode = extractRadix(block, 100, 8, 8);
2667
2668 info.path = extractString(block, 345, 155); // prefix
2669 String path = extractString(block, 0, 100);
2670 if (path.length() > 0) {
2671 if (info.path.length() > 0) info.path += '/';
2672 info.path += path;
2673 }
2674
2675 // tar link indicator field: 1 byte at offset 156 in the header.
2676 int typeChar = block[156];
2677 if (typeChar == 'x') {
2678 // pax extended header, so we need to read that
2679 gotHeader = readPaxExtendedHeader(instream, info);
2680 if (gotHeader) {
2681 // and after a pax extended header comes another real header -- read
2682 // that to find the real file type
2683 gotHeader = readTarHeader(instream, block);
2684 }
2685 if (!gotHeader) throw new IOException("Bad or missing pax header");
2686
2687 typeChar = block[156];
2688 }
2689
2690 switch (typeChar) {
2691 case '0': info.type = FullBackup.TYPE_FILE; break;
2692 case '5': info.type = FullBackup.TYPE_DIRECTORY; break;
2693 case 0: {
2694 // presume EOF
2695 return null;
2696 }
2697 default: {
2698 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
2699 throw new IOException("Unknown entity type " + typeChar);
2700 }
2701 }
2702
2703 // Parse out the path
2704 //
2705 // first: apps/shared/unrecognized
2706 if (FullBackup.SHARED_PREFIX.regionMatches(0,
2707 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
2708 // File in shared storage. !!! TODO: implement this.
2709 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
2710 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
2711 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
2712 info.path, 0, FullBackup.APPS_PREFIX.length())) {
2713 // App content! Parse out the package name and domain
2714
2715 // strip the apps/ prefix
2716 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
2717
2718 // extract the package name
2719 int slash = info.path.indexOf('/');
2720 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
2721 info.packageName = info.path.substring(0, slash);
2722 info.path = info.path.substring(slash+1);
2723
2724 // if it's a manifest we're done, otherwise parse out the domains
2725 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2726 slash = info.path.indexOf('/');
2727 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
2728 info.domain = info.path.substring(0, slash);
2729 // validate that it's one of the domains we understand
2730 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
2731 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
2732 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
2733 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
2734 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
2735 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
2736 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
2737 throw new IOException("Unrecognized domain " + info.domain);
2738 }
2739
2740 info.path = info.path.substring(slash + 1);
2741 }
2742 }
2743 }
2744 return info;
2745 }
2746
2747 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
2748 int nRead = instream.read(block, 0, 512);
2749 if (nRead > 0 && nRead != 512) {
2750 // if we read only a partial block, then things are
2751 // clearly screwed up. terminate the restore.
2752 throw new IOException("Partial header block: " + nRead);
2753 }
2754 return (nRead > 0);
2755 }
2756
2757 // overwrites 'info' fields based on the pax extended header
2758 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
2759 throws IOException {
2760 // We should never see a pax extended header larger than this
2761 if (info.size > 32*1024) {
2762 Slog.w(TAG, "Suspiciously large pax header size " + info.size
2763 + " - aborting");
2764 throw new IOException("Sanity failure: pax header size " + info.size);
2765 }
2766
2767 // read whole blocks, not just the content size
2768 int numBlocks = (int)((info.size + 511) >> 9);
2769 byte[] data = new byte[numBlocks * 512];
2770 int nRead = instream.read(data);
2771 if (nRead != data.length) {
2772 return false;
2773 }
2774
2775 final int contentSize = (int) info.size;
2776 int offset = 0;
2777 do {
2778 // extract the line at 'offset'
2779 int eol = offset+1;
2780 while (eol < contentSize && data[eol] != ' ') eol++;
2781 if (eol >= contentSize) {
2782 // error: we just hit EOD looking for the end of the size field
2783 throw new IOException("Invalid pax data");
2784 }
2785 // eol points to the space between the count and the key
2786 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
2787 int key = eol + 1; // start of key=value
2788 eol = offset + linelen - 1; // trailing LF
2789 int value;
2790 for (value = key+1; data[value] != '=' && value <= eol; value++);
2791 if (value > eol) {
2792 throw new IOException("Invalid pax declaration");
2793 }
2794
2795 // pax requires that key/value strings be in UTF-8
2796 String keyStr = new String(data, key, value-key, "UTF-8");
2797 // -1 to strip the trailing LF
2798 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
2799
2800 if ("path".equals(keyStr)) {
2801 info.path = valStr;
2802 } else if ("size".equals(keyStr)) {
2803 info.size = Long.parseLong(valStr);
2804 } else {
2805 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
2806 }
2807
2808 offset += linelen;
2809 } while (offset < contentSize);
2810
2811 return true;
2812 }
2813
2814 long extractRadix(byte[] data, int offset, int maxChars, int radix)
2815 throws IOException {
2816 long value = 0;
2817 final int end = offset + maxChars;
2818 for (int i = offset; i < end; i++) {
2819 final byte b = data[i];
2820 if (b == 0 || b == ' ') break;
2821 if (b < '0' || b > ('0' + radix - 1)) {
2822 throw new IOException("Invalid number in header");
2823 }
2824 value = radix * value + (b - '0');
2825 }
2826 return value;
2827 }
2828
2829 String extractString(byte[] data, int offset, int maxChars) throws IOException {
2830 final int end = offset + maxChars;
2831 int eos = offset;
2832 // tar string fields can end with either NUL or SPC
2833 while (eos < end && data[eos] != 0 && data[eos] != ' ') eos++;
2834 return new String(data, offset, eos-offset, "US-ASCII");
2835 }
2836
2837 void sendStartRestore() {
2838 if (mObserver != null) {
2839 try {
2840 mObserver.onStartRestore();
2841 } catch (RemoteException e) {
2842 Slog.w(TAG, "full restore observer went away: startRestore");
2843 mObserver = null;
2844 }
2845 }
2846 }
2847
2848 void sendOnRestorePackage(String name) {
2849 if (mObserver != null) {
2850 try {
2851 // TODO: use a more user-friendly name string
2852 mObserver.onRestorePackage(name);
2853 } catch (RemoteException e) {
2854 Slog.w(TAG, "full restore observer went away: restorePackage");
2855 mObserver = null;
2856 }
2857 }
2858 }
2859
2860 void sendEndRestore() {
2861 if (mObserver != null) {
2862 try {
2863 mObserver.onEndRestore();
2864 } catch (RemoteException e) {
2865 Slog.w(TAG, "full restore observer went away: endRestore");
2866 mObserver = null;
2867 }
2868 }
2869 }
2870 }
2871
Christopher Tatedf01dea2009-06-09 20:45:02 -07002872 // ----- Restore handling -----
2873
Christopher Tate78dd4a72009-11-04 11:49:08 -08002874 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
2875 // If the target resides on the system partition, we allow it to restore
2876 // data from the like-named package in a restore set even if the signatures
2877 // do not match. (Unlike general applications, those flashed to the system
2878 // partition will be signed with the device's platform certificate, so on
2879 // different phones the same system app will have different signatures.)
2880 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002881 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08002882 return true;
2883 }
2884
Christopher Tate20efdf6b2009-06-18 19:41:36 -07002885 // Allow unsigned apps, but not signed on one device and unsigned on the other
2886 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08002887 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002888 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07002889 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07002890 if ((storedSigs == null || storedSigs.length == 0)
2891 && (deviceSigs == null || deviceSigs.length == 0)) {
2892 return true;
2893 }
2894 if (storedSigs == null || deviceSigs == null) {
2895 return false;
2896 }
2897
Christopher Tateabce4e82009-06-18 18:35:32 -07002898 // !!! TODO: this demands that every stored signature match one
2899 // that is present on device, and does not demand the converse.
2900 // Is this this right policy?
2901 int nStored = storedSigs.length;
2902 int nDevice = deviceSigs.length;
2903
2904 for (int i=0; i < nStored; i++) {
2905 boolean match = false;
2906 for (int j=0; j < nDevice; j++) {
2907 if (storedSigs[i].equals(deviceSigs[j])) {
2908 match = true;
2909 break;
2910 }
2911 }
2912 if (!match) {
2913 return false;
2914 }
2915 }
2916 return true;
2917 }
2918
Christopher Tate44a27902010-01-27 17:15:49 -08002919 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07002920 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07002921 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07002922 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08002923 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07002924 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08002925 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07002926 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002927
Christopher Tate5cbbf562009-06-22 16:44:51 -07002928 class RestoreRequest {
2929 public PackageInfo app;
2930 public int storedAppVersion;
2931
2932 RestoreRequest(PackageInfo _app, int _version) {
2933 app = _app;
2934 storedAppVersion = _version;
2935 }
2936 }
2937
Christopher Tate44a27902010-01-27 17:15:49 -08002938 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07002939 long restoreSetToken, PackageInfo targetPackage, int pmToken,
2940 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07002941 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07002942 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002943 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08002944 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08002945 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07002946 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07002947
2948 try {
2949 mStateDir = new File(mBaseStateDir, transport.transportDirName());
2950 } catch (RemoteException e) {
2951 // can't happen; the transport is local
2952 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002953 }
2954
Christopher Tatedf01dea2009-06-09 20:45:02 -07002955 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07002956 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002957 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08002958 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08002959 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07002960
Christopher Tateb49ceb32010-02-08 16:22:24 -08002961 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07002962 int error = -1; // assume error
2963
Dan Egnorefe52642009-06-24 00:16:33 -07002964 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07002965 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07002966 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002967 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07002968
Dan Egnorefe52642009-06-24 00:16:33 -07002969 // Get the list of all packages which have backup enabled.
2970 // (Include the Package Manager metadata pseudo-package first.)
2971 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
2972 PackageInfo omPackage = new PackageInfo();
2973 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
2974 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07002975
Dan Egnorefe52642009-06-24 00:16:33 -07002976 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08002977 if (mTargetPackage == null) {
2978 restorePackages.addAll(agentPackages);
2979 } else {
2980 // Just one package to attempt restore of
2981 restorePackages.add(mTargetPackage);
2982 }
Dan Egnorefe52642009-06-24 00:16:33 -07002983
Christopher Tate7d562ec2009-06-25 18:03:43 -07002984 // let the observer know that we're running
2985 if (mObserver != null) {
2986 try {
2987 // !!! TODO: get an actual count from the transport after
2988 // its startRestore() runs?
2989 mObserver.restoreStarting(restorePackages.size());
2990 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002991 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002992 mObserver = null;
2993 }
2994 }
2995
Dan Egnor01445162009-09-21 17:04:05 -07002996 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
2997 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002998 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002999 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003000 return;
3001 }
3002
3003 String packageName = mTransport.nextRestorePackage();
3004 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003005 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003006 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003007 return;
3008 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003009 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003010 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003011 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003012 return;
3013 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003014 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003015 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003016 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003017 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003018 return;
3019 }
3020
3021 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003022 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003023 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003024 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3025 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003026
Christopher Tate8c032472009-07-02 14:28:47 -07003027 // Verify that the backup set includes metadata. If not, we can't do
3028 // signature/version verification etc, so we simply do not proceed with
3029 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003030 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003031 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003032 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003033 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003034 return;
3035 }
3036
Christopher Tate7d562ec2009-06-25 18:03:43 -07003037 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003038 for (;;) {
3039 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003040
Dan Egnorefe52642009-06-24 00:16:33 -07003041 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003042 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003043 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003044 return;
3045 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003046 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003047 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003048 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003049
Christopher Tate7d562ec2009-06-25 18:03:43 -07003050 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003051 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003052 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003053 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003054 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003055 mObserver = null;
3056 }
3057 }
3058
Dan Egnorefe52642009-06-24 00:16:33 -07003059 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3060 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003061 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003063 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003064 continue;
3065 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003066
Dan Egnorbb9001c2009-07-27 12:20:13 -07003067 PackageInfo packageInfo;
3068 try {
3069 int flags = PackageManager.GET_SIGNATURES;
3070 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3071 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003072 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003073 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003074 "Package missing on device");
3075 continue;
3076 }
3077
Dan Egnorefe52642009-06-24 00:16:33 -07003078 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003079 // Data is from a "newer" version of the app than we have currently
3080 // installed. If the app has not declared that it is prepared to
3081 // handle this case, we do not attempt the restore.
3082 if ((packageInfo.applicationInfo.flags
3083 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3084 String message = "Version " + metaInfo.versionCode
3085 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003086 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003087 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3088 packageName, message);
3089 continue;
3090 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003091 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003092 + " > installed " + packageInfo.versionCode
3093 + " but restoreAnyVersion");
3094 }
Dan Egnorefe52642009-06-24 00:16:33 -07003095 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003096
Christopher Tate78dd4a72009-11-04 11:49:08 -08003097 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003098 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003099 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003100 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003101 continue;
3102 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003103
Joe Onorato8a9b2202010-02-26 18:56:32 -08003104 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003105 + " restore version [" + metaInfo.versionCode
3106 + "] is compatible with installed version ["
3107 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003108
Christopher Tate3de55bc2010-03-12 17:28:08 -08003109 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003110 IBackupAgent agent = bindToAgentSynchronous(
3111 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003112 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003113 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003114 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003115 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003116 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003117 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003118 }
3119
Christopher Tate5e1ab332009-09-01 20:32:49 -07003120 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003121 try {
Chris Tate249345b2010-10-29 12:57:04 -07003122 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3123 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003124 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003125 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003126 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003127 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003128
3129 // The agent was probably running with a stub Application object,
3130 // which isn't a valid run mode for the main app logic. Shut
3131 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003132 // usual full initialization. Note that this is only done for
3133 // full-system restores: when a single app has requested a restore,
3134 // it is explicitly not killed following that operation.
3135 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003136 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003137 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003138 + packageInfo.applicationInfo.processName);
3139 mActivityManager.killApplicationProcess(
3140 packageInfo.applicationInfo.processName,
3141 packageInfo.applicationInfo.uid);
3142 }
Dan Egnorefe52642009-06-24 00:16:33 -07003143 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003144 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003145
3146 // if we get this far, report success to the observer
3147 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003148 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003149 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003150 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003151 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003152 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003153 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003154
Dan Egnorefe52642009-06-24 00:16:33 -07003155 try {
3156 mTransport.finishRestore();
3157 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003158 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003159 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003160
3161 if (mObserver != null) {
3162 try {
3163 mObserver.restoreFinished(error);
3164 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003165 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003166 }
3167 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003168
Christopher Tate84725812010-02-04 15:52:40 -08003169 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003170 // ancestral dataset, as well as the set of apps that are possibly
3171 // restoreable from the dataset
3172 if (mTargetPackage == null && pmAgent != null) {
3173 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003174 mAncestralToken = mToken;
3175 writeRestoreTokens();
3176 }
3177
Christopher Tate1bb69062010-02-19 17:02:12 -08003178 // We must under all circumstances tell the Package Manager to
3179 // proceed with install notifications if it's waiting for us.
3180 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003181 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003182 try {
3183 mPackageManagerBinder.finishPackageInstall(mPmToken);
3184 } catch (RemoteException e) { /* can't happen */ }
3185 }
3186
Christopher Tate73a3cb32010-12-13 18:27:26 -08003187 // Furthermore we need to reset the session timeout clock
3188 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3189 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3190 TIMEOUT_RESTORE_INTERVAL);
3191
Christopher Tateb6787f22009-07-02 17:40:45 -07003192 // done; we can finally release the wakelock
3193 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003194 }
3195 }
3196
Dan Egnorefe52642009-06-24 00:16:33 -07003197 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003198 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3199 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003200 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003201 final String packageName = app.packageName;
3202
Joe Onorato8a9b2202010-02-26 18:56:32 -08003203 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003204
Christopher Tatec7b31e32009-06-10 15:49:30 -07003205 // !!! TODO: get the dirs from the transport
3206 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003207 File newStateName = new File(mStateDir, packageName + ".new");
3208 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003209
Dan Egnorbb9001c2009-07-27 12:20:13 -07003210 ParcelFileDescriptor backupData = null;
3211 ParcelFileDescriptor newState = null;
3212
Christopher Tate4a627c72011-04-01 14:43:32 -07003213 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003214 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003215 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003216 backupData = ParcelFileDescriptor.open(backupDataName,
3217 ParcelFileDescriptor.MODE_READ_WRITE |
3218 ParcelFileDescriptor.MODE_CREATE |
3219 ParcelFileDescriptor.MODE_TRUNCATE);
3220
Dan Egnor01445162009-09-21 17:04:05 -07003221 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003222 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003223 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003224 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003225 }
3226
3227 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07003228 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07003229 backupData = ParcelFileDescriptor.open(backupDataName,
3230 ParcelFileDescriptor.MODE_READ_ONLY);
3231
Dan Egnorbb9001c2009-07-27 12:20:13 -07003232 newState = ParcelFileDescriptor.open(newStateName,
3233 ParcelFileDescriptor.MODE_READ_WRITE |
3234 ParcelFileDescriptor.MODE_CREATE |
3235 ParcelFileDescriptor.MODE_TRUNCATE);
3236
Christopher Tate44a27902010-01-27 17:15:49 -08003237 // Kick off the restore, checking for hung agents
3238 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
3239 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
3240 boolean success = waitUntilOperationComplete(token);
3241
3242 if (!success) {
3243 throw new RuntimeException("restore timeout");
3244 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003245
3246 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07003247 //
3248 // !!! TODO: the restored data should be migrated on the server
3249 // side into the current dataset. In that case the new state file
3250 // we just created would reflect the data already extant in the
3251 // backend, so there'd be nothing more to do. Until that happens,
3252 // however, we need to make sure that we record the data to the
3253 // current backend dataset. (Yes, this means shipping the data over
3254 // the wire in both directions. That's bad, but consistency comes
3255 // first, then efficiency.) Once we introduce server-side data
3256 // migration to the newly-restored device's dataset, we will change
3257 // the following from a discard of the newly-written state to the
3258 // "correct" operation of renaming into the canonical state blob.
3259 newStateName.delete(); // TODO: remove; see above comment
3260 //newStateName.renameTo(savedStateName); // TODO: replace with this
3261
Dan Egnorbb9001c2009-07-27 12:20:13 -07003262 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003263 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003264 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003265 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003266 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07003267
Christopher Tate96733042009-07-20 14:49:13 -07003268 // If the agent fails restore, it might have put the app's data
3269 // into an incoherent state. For consistency we wipe its data
3270 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07003271 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07003272 } finally {
3273 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003274 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
3275 try { if (newState != null) newState.close(); } catch (IOException e) {}
3276 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07003277 synchronized (mCurrentOperations) {
3278 mCurrentOperations.delete(token);
3279 }
Chris Tate249345b2010-10-29 12:57:04 -07003280
3281 // If we know a priori that we'll need to perform a full post-restore backup
3282 // pass, clear the new state file data. This means we're discarding work that
3283 // was just done by the app's agent, but this way the agent doesn't need to
3284 // take any special action based on global device state.
3285 if (needFullBackup) {
3286 newStateName.delete();
3287 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003288 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003289 }
3290 }
3291
Christopher Tate44a27902010-01-27 17:15:49 -08003292 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003293 IBackupTransport mTransport;
3294 PackageInfo mPackage;
3295
Christopher Tate44a27902010-01-27 17:15:49 -08003296 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003297 mTransport = transport;
3298 mPackage = packageInfo;
3299 }
3300
Christopher Tateee0e78a2009-07-02 11:17:03 -07003301 public void run() {
3302 try {
3303 // Clear the on-device backup state to ensure a full backup next time
3304 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
3305 File stateFile = new File(stateDir, mPackage.packageName);
3306 stateFile.delete();
3307
3308 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07003309 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003310 mTransport.clearBackupData(mPackage);
3311 } catch (RemoteException e) {
3312 // can't happen; the transport is local
3313 } finally {
3314 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07003315 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003316 mTransport.finishBackup();
3317 } catch (RemoteException e) {
3318 // can't happen; the transport is local
3319 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003320
3321 // Last but not least, release the cpu
3322 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003323 }
3324 }
3325 }
3326
Christopher Tate44a27902010-01-27 17:15:49 -08003327 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003328 HashSet<String> mQueue;
3329
Christopher Tate44a27902010-01-27 17:15:49 -08003330 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003331 mQueue = transportNames;
3332 }
3333
Christopher Tate4cc86e12009-09-21 19:36:51 -07003334 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003335 try {
3336 for (String transportName : mQueue) {
3337 IBackupTransport transport = getTransport(transportName);
3338 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003339 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003340 continue;
3341 }
3342
Joe Onorato8a9b2202010-02-26 18:56:32 -08003343 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003344 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07003345 long startRealtime = SystemClock.elapsedRealtime();
3346 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07003347
Christopher Tate4cc86e12009-09-21 19:36:51 -07003348 if (status == BackupConstants.TRANSPORT_OK) {
3349 status = transport.finishBackup();
3350 }
3351
3352 // Okay, the wipe really happened. Clean up our local bookkeeping.
3353 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003354 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07003355 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003356 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07003357 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003358 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003359 synchronized (mQueueLock) {
3360 recordInitPendingLocked(false, transportName);
3361 }
Dan Egnor726247c2009-09-29 19:12:31 -07003362 } else {
3363 // If this didn't work, requeue this one and try again
3364 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08003365 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003366 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003367 synchronized (mQueueLock) {
3368 recordInitPendingLocked(true, transportName);
3369 }
3370 // do this via another alarm to make sure of the wakelock states
3371 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003372 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07003373 + transportName + " resched in " + delay);
3374 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
3375 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003376 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07003377 }
3378 } catch (RemoteException e) {
3379 // can't happen; the transports are local
3380 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003381 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003382 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08003383 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07003384 mWakelock.release();
3385 }
3386 }
3387 }
3388
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003389 private void dataChangedImpl(String packageName) {
3390 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3391 dataChangedImpl(packageName, targets);
3392 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003393
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003394 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07003395 // Record that we need a backup pass for the caller. Since multiple callers
3396 // may share a uid, we need to note all candidates within that uid and schedule
3397 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003398 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003399
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003400 if (targets == null) {
3401 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3402 + " uid=" + Binder.getCallingUid());
3403 return;
3404 }
3405
3406 synchronized (mQueueLock) {
3407 // Note that this client has made data changes that need to be backed up
3408 for (ApplicationInfo app : targets) {
3409 // validate the caller-supplied package name against the known set of
3410 // packages associated with this uid
3411 if (app.packageName.equals(packageName)) {
3412 // Add the caller to the set of pending backups. If there is
3413 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07003414 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08003415 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003416 // Journal this request in case of crash. The put()
3417 // operation returned null when this package was not already
3418 // in the set; we want to avoid touching the disk redundantly.
3419 writeToJournalLocked(packageName);
3420
3421 if (DEBUG) {
3422 int numKeys = mPendingBackups.size();
3423 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
3424 for (BackupRequest b : mPendingBackups.values()) {
3425 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
3426 }
3427 }
3428 }
3429 }
3430 }
3431 }
3432 }
3433
3434 // Note: packageName is currently unused, but may be in the future
3435 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07003436 // If the caller does not hold the BACKUP permission, it can only request a
3437 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07003438 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07003439 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003440 synchronized (mBackupParticipants) {
3441 return mBackupParticipants.get(Binder.getCallingUid());
3442 }
3443 }
3444
3445 // a caller with full permission can ask to back up any participating app
3446 // !!! TODO: allow backup of ANY app?
3447 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
3448 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07003449 int N = mBackupParticipants.size();
3450 for (int i = 0; i < N; i++) {
3451 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3452 if (s != null) {
3453 targets.addAll(s);
3454 }
3455 }
3456 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003457 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07003458 }
Christopher Tate46758122009-05-06 11:22:00 -07003459
Christopher Tatecde87f42009-06-12 12:55:53 -07003460 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003461 RandomAccessFile out = null;
3462 try {
3463 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
3464 out = new RandomAccessFile(mJournal, "rws");
3465 out.seek(out.length());
3466 out.writeUTF(str);
3467 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003468 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003469 mJournal = null;
3470 } finally {
3471 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07003472 }
3473 }
3474
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003475 // ----- IBackupManager binder interface -----
3476
3477 public void dataChanged(final String packageName) {
3478 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3479 if (targets == null) {
3480 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3481 + " uid=" + Binder.getCallingUid());
3482 return;
3483 }
3484
3485 mBackupHandler.post(new Runnable() {
3486 public void run() {
3487 dataChangedImpl(packageName, targets);
3488 }
3489 });
3490 }
3491
Christopher Tateee0e78a2009-07-02 11:17:03 -07003492 // Clear the given package's backup data from the current transport
3493 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003494 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003495 PackageInfo info;
3496 try {
3497 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
3498 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003499 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003500 return;
3501 }
3502
3503 // If the caller does not hold the BACKUP permission, it can only request a
3504 // wipe of its own backed-up data.
3505 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07003506 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07003507 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
3508 apps = mBackupParticipants.get(Binder.getCallingUid());
3509 } else {
3510 // a caller with full permission can ask to back up any participating app
3511 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08003512 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003513 apps = new HashSet<ApplicationInfo>();
3514 int N = mBackupParticipants.size();
3515 for (int i = 0; i < N; i++) {
3516 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3517 if (s != null) {
3518 apps.addAll(s);
3519 }
3520 }
3521 }
3522
3523 // now find the given package in the set of candidate apps
3524 for (ApplicationInfo app : apps) {
3525 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003526 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003527 // found it; fire off the clear request
3528 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07003529 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07003530 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003531 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
3532 new ClearParams(getTransport(mCurrentTransport), info));
3533 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07003534 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003535 }
3536 break;
3537 }
3538 }
3539 }
3540
Christopher Tateace7f092009-06-15 18:07:25 -07003541 // Run a backup pass immediately for any applications that have declared
3542 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07003543 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04003544 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07003545
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07003547 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003548 // Because the alarms we are using can jitter, and we want an *immediate*
3549 // backup pass to happen, we restart the timer beginning with "next time,"
3550 // then manually fire the backup trigger intent ourselves.
3551 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07003552 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07003553 mRunBackupIntent.send();
3554 } catch (PendingIntent.CanceledException e) {
3555 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08003556 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07003557 }
Christopher Tate46758122009-05-06 11:22:00 -07003558 }
3559 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003560
Christopher Tate4a627c72011-04-01 14:43:32 -07003561 // Run a *full* backup pass for the given package, writing the resulting data stream
3562 // to the supplied file descriptor. This method is synchronous and does not return
3563 // to the caller until the backup has been completed.
3564 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
3565 boolean doAllApps, String[] pkgList) {
3566 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3567
3568 // Validate
3569 if (!doAllApps) {
3570 if (!includeShared) {
3571 // If we're backing up shared data (sdcard or equivalent), then we can run
3572 // without any supplied app names. Otherwise, we'd be doing no work, so
3573 // report the error.
3574 if (pkgList == null || pkgList.length == 0) {
3575 throw new IllegalArgumentException(
3576 "Backup requested but neither shared nor any apps named");
3577 }
3578 }
3579 }
3580
3581 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
3582 + " shared=" + includeShared + " all=" + doAllApps
3583 + " pkgs=" + pkgList);
3584
3585 long oldId = Binder.clearCallingIdentity();
3586 try {
3587 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
3588 doAllApps, pkgList);
3589 final int token = generateToken();
3590 synchronized (mFullConfirmations) {
3591 mFullConfirmations.put(token, params);
3592 }
3593
Christopher Tate75a99702011-05-18 16:28:19 -07003594 // start up the confirmation UI
3595 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
3596 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
3597 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07003598 mFullConfirmations.delete(token);
3599 return;
3600 }
Christopher Tate75a99702011-05-18 16:28:19 -07003601
3602 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07003603 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3604
3605 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07003606 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003607
3608 // wait for the backup to be performed
3609 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
3610 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003611 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07003612 try {
3613 fd.close();
3614 } catch (IOException e) {
3615 // just eat it
3616 }
Christopher Tate75a99702011-05-18 16:28:19 -07003617 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07003618 }
Christopher Tate75a99702011-05-18 16:28:19 -07003619 if (DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
3620 }
3621
3622 public void fullRestore(ParcelFileDescriptor fd) {
3623 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3624 Slog.i(TAG, "Beginning full restore...");
3625
3626 long oldId = Binder.clearCallingIdentity();
3627
3628 try {
3629 FullRestoreParams params = new FullRestoreParams(fd);
3630 final int token = generateToken();
3631 synchronized (mFullConfirmations) {
3632 mFullConfirmations.put(token, params);
3633 }
3634
3635 // start up the confirmation UI
3636 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
3637 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
3638 Slog.e(TAG, "Unable to launch full restore confirmation");
3639 mFullConfirmations.delete(token);
3640 return;
3641 }
3642
3643 // make sure the screen is lit for the user interaction
3644 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3645
3646 // start the confirmation countdown
3647 startConfirmationTimeout(token, params);
3648
3649 // wait for the restore to be performed
3650 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
3651 waitForCompletion(params);
3652 } finally {
3653 try {
3654 fd.close();
3655 } catch (IOException e) {
3656 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
3657 }
3658 Binder.restoreCallingIdentity(oldId);
3659 Slog.i(TAG, "Full restore completed");
3660 }
3661 }
3662
3663 boolean startConfirmationUi(int token, String action) {
3664 try {
3665 Intent confIntent = new Intent(action);
3666 confIntent.setClassName("com.android.backupconfirm",
3667 "com.android.backupconfirm.BackupRestoreConfirmation");
3668 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
3669 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3670 mContext.startActivity(confIntent);
3671 } catch (ActivityNotFoundException e) {
3672 return false;
3673 }
3674 return true;
3675 }
3676
3677 void startConfirmationTimeout(int token, FullParams params) {
3678 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
3679 + TIMEOUT_FULL_CONFIRMATION + " millis");
3680 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
3681 token, 0, params);
3682 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07003683 }
3684
3685 void waitForCompletion(FullParams params) {
3686 synchronized (params.latch) {
3687 while (params.latch.get() == false) {
3688 try {
3689 params.latch.wait();
3690 } catch (InterruptedException e) { /* never interrupted */ }
3691 }
3692 }
3693 }
3694
3695 void signalFullBackupRestoreCompletion(FullParams params) {
3696 synchronized (params.latch) {
3697 params.latch.set(true);
3698 params.latch.notifyAll();
3699 }
3700 }
3701
3702 // Confirm that the previously-requested full backup/restore operation can proceed. This
3703 // is used to require a user-facing disclosure about the operation.
3704 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
3705 IFullBackupRestoreObserver observer) {
3706 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
3707 + " allow=" + allow);
3708
3709 // TODO: possibly require not just this signature-only permission, but even
3710 // require that the specific designated confirmation-UI app uid is the caller?
3711 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3712
3713 long oldId = Binder.clearCallingIdentity();
3714 try {
3715
3716 FullParams params;
3717 synchronized (mFullConfirmations) {
3718 params = mFullConfirmations.get(token);
3719 if (params != null) {
3720 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
3721 mFullConfirmations.delete(token);
3722
3723 if (allow) {
3724 params.observer = observer;
3725 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07003726 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07003727 : MSG_RUN_FULL_RESTORE;
3728
Christopher Tate75a99702011-05-18 16:28:19 -07003729 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07003730 mWakelock.acquire();
3731 Message msg = mBackupHandler.obtainMessage(verb, params);
3732 mBackupHandler.sendMessage(msg);
3733 } else {
3734 Slog.w(TAG, "User rejected full backup/restore operation");
3735 // indicate completion without having actually transferred any data
3736 signalFullBackupRestoreCompletion(params);
3737 }
3738 } else {
3739 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
3740 }
3741 }
3742 } finally {
3743 Binder.restoreCallingIdentity(oldId);
3744 }
3745 }
3746
Christopher Tate8031a3d2009-07-06 16:36:05 -07003747 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07003748 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07003749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07003750 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07003751
Joe Onorato8a9b2202010-02-26 18:56:32 -08003752 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003753
Christopher Tate6ef58a12009-06-29 14:56:28 -07003754 boolean wasEnabled = mEnabled;
3755 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07003756 Settings.Secure.putInt(mContext.getContentResolver(),
3757 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07003758 mEnabled = enable;
3759 }
3760
Christopher Tate49401dd2009-07-01 12:34:29 -07003761 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07003762 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07003763 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07003764 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07003765 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07003766 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08003767 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003768
Christopher Tateb6787f22009-07-02 17:40:45 -07003769 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003770
3771 // This also constitutes an opt-out, so we wipe any data for
3772 // this device from the backend. We start that process with
3773 // an alarm in order to guarantee wakelock states.
3774 if (wasEnabled && mProvisioned) {
3775 // NOTE: we currently flush every registered transport, not just
3776 // the currently-active one.
3777 HashSet<String> allTransports;
3778 synchronized (mTransports) {
3779 allTransports = new HashSet<String>(mTransports.keySet());
3780 }
3781 // build the set of transports for which we are posting an init
3782 for (String transport : allTransports) {
3783 recordInitPendingLocked(true, transport);
3784 }
3785 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
3786 mRunInitIntent);
3787 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07003788 }
3789 }
Christopher Tate49401dd2009-07-01 12:34:29 -07003790 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07003791
Christopher Tatecce9da52010-02-03 15:11:15 -08003792 // Enable/disable automatic restore of app data at install time
3793 public void setAutoRestore(boolean doAutoRestore) {
3794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3795 "setBackupEnabled");
3796
Joe Onorato8a9b2202010-02-26 18:56:32 -08003797 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08003798
3799 synchronized (this) {
3800 Settings.Secure.putInt(mContext.getContentResolver(),
3801 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
3802 mAutoRestore = doAutoRestore;
3803 }
3804 }
3805
Christopher Tate8031a3d2009-07-06 16:36:05 -07003806 // Mark the backup service as having been provisioned
3807 public void setBackupProvisioned(boolean available) {
3808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3809 "setBackupProvisioned");
3810
3811 boolean wasProvisioned = mProvisioned;
3812 synchronized (this) {
3813 Settings.Secure.putInt(mContext.getContentResolver(),
3814 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
3815 mProvisioned = available;
3816 }
3817
3818 synchronized (mQueueLock) {
3819 if (available && !wasProvisioned && mEnabled) {
3820 // we're now good to go, so start the backup alarms
3821 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
3822 } else if (!available) {
3823 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08003824 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07003825 mAlarmManager.cancel(mRunBackupIntent);
3826 }
3827 }
3828 }
3829
3830 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07003831 // We used to use setInexactRepeating(), but that may be linked to
3832 // backups running at :00 more often than not, creating load spikes.
3833 // Schedule at an exact time for now, and also add a bit of "fuzz".
3834
3835 Random random = new Random();
3836 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
3837 random.nextInt(FUZZ_MILLIS);
3838 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
3839 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07003840 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07003841 }
3842
Christopher Tate6ef58a12009-06-29 14:56:28 -07003843 // Report whether the backup mechanism is currently enabled
3844 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04003845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07003846 return mEnabled; // no need to synchronize just to read it
3847 }
3848
Christopher Tate91717492009-06-26 21:07:13 -07003849 // Report the name of the currently active transport
3850 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04003851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07003852 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08003853 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07003854 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07003855 }
3856
Christopher Tate91717492009-06-26 21:07:13 -07003857 // Report all known, available backup transports
3858 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07003859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07003860
Christopher Tate91717492009-06-26 21:07:13 -07003861 String[] list = null;
3862 ArrayList<String> known = new ArrayList<String>();
3863 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
3864 if (entry.getValue() != null) {
3865 known.add(entry.getKey());
3866 }
3867 }
3868
3869 if (known.size() > 0) {
3870 list = new String[known.size()];
3871 known.toArray(list);
3872 }
3873 return list;
3874 }
3875
3876 // Select which transport to use for the next backup operation. If the given
3877 // name is not one of the available transports, no action is taken and the method
3878 // returns null.
3879 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04003880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07003881
3882 synchronized (mTransports) {
3883 String prevTransport = null;
3884 if (mTransports.get(transport) != null) {
3885 prevTransport = mCurrentTransport;
3886 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07003887 Settings.Secure.putString(mContext.getContentResolver(),
3888 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003889 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07003890 + " returning " + prevTransport);
3891 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003892 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07003893 }
3894 return prevTransport;
3895 }
Christopher Tate043dadc2009-06-02 16:11:00 -07003896 }
3897
Christopher Tatef5e1c292010-12-08 18:40:26 -08003898 // Supply the configuration Intent for the given transport. If the name is not one
3899 // of the available transports, or if the transport does not supply any configuration
3900 // UI, the method returns null.
3901 public Intent getConfigurationIntent(String transportName) {
3902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3903 "getConfigurationIntent");
3904
3905 synchronized (mTransports) {
3906 final IBackupTransport transport = mTransports.get(transportName);
3907 if (transport != null) {
3908 try {
3909 final Intent intent = transport.configurationIntent();
3910 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
3911 + intent);
3912 return intent;
3913 } catch (RemoteException e) {
3914 /* fall through to return null */
3915 }
3916 }
3917 }
3918
3919 return null;
3920 }
3921
3922 // Supply the configuration summary string for the given transport. If the name is
3923 // not one of the available transports, or if the transport does not supply any
3924 // summary / destination string, the method can return null.
3925 //
3926 // This string is used VERBATIM as the summary text of the relevant Settings item!
3927 public String getDestinationString(String transportName) {
3928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3929 "getConfigurationIntent");
3930
3931 synchronized (mTransports) {
3932 final IBackupTransport transport = mTransports.get(transportName);
3933 if (transport != null) {
3934 try {
3935 final String text = transport.currentDestinationString();
3936 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
3937 return text;
3938 } catch (RemoteException e) {
3939 /* fall through to return null */
3940 }
3941 }
3942 }
3943
3944 return null;
3945 }
3946
Christopher Tate043dadc2009-06-02 16:11:00 -07003947 // Callback: a requested backup agent has been instantiated. This should only
3948 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07003950 synchronized(mAgentConnectLock) {
3951 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003952 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07003953 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
3954 mConnectedAgent = agent;
3955 mConnecting = false;
3956 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003957 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07003958 + " claiming agent connected");
3959 }
3960 mAgentConnectLock.notifyAll();
3961 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003962 }
3963
3964 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
3965 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07003966 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07003967 public void agentDisconnected(String packageName) {
3968 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07003969 synchronized(mAgentConnectLock) {
3970 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
3971 mConnectedAgent = null;
3972 mConnecting = false;
3973 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003974 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07003975 + " claiming agent disconnected");
3976 }
3977 mAgentConnectLock.notifyAll();
3978 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003979 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003980
Christopher Tate1bb69062010-02-19 17:02:12 -08003981 // An application being installed will need a restore pass, then the Package Manager
3982 // will need to be told when the restore is finished.
3983 public void restoreAtInstall(String packageName, int token) {
3984 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003985 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08003986 + " attemping install-time restore");
3987 return;
3988 }
3989
3990 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003991 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08003992 + " token=" + Integer.toHexString(token));
3993
Christopher Tatef0872722010-02-25 15:22:48 -08003994 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08003995 // okay, we're going to attempt a restore of this package from this restore set.
3996 // The eventual message back into the Package Manager to run the post-install
3997 // steps for 'token' will be issued from the restore handling code.
3998
3999 // We can use a synthetic PackageInfo here because:
4000 // 1. We know it's valid, since the Package Manager supplied the name
4001 // 2. Only the packageName field will be used by the restore code
4002 PackageInfo pkg = new PackageInfo();
4003 pkg.packageName = packageName;
4004
4005 mWakelock.acquire();
4006 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4007 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004008 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004009 mBackupHandler.sendMessage(msg);
4010 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004011 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4012 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004013 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004014 try {
4015 mPackageManagerBinder.finishPackageInstall(token);
4016 } catch (RemoteException e) { /* can't happen */ }
4017 }
4018 }
4019
Christopher Tate8c850b72009-06-07 19:33:20 -07004020 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004021 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4022 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4023 + " transport=" + transport);
4024
4025 boolean needPermission = true;
4026 if (transport == null) {
4027 transport = mCurrentTransport;
4028
4029 if (packageName != null) {
4030 PackageInfo app = null;
4031 try {
4032 app = mPackageManager.getPackageInfo(packageName, 0);
4033 } catch (NameNotFoundException nnf) {
4034 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4035 throw new IllegalArgumentException("Package " + packageName + " not found");
4036 }
4037
4038 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4039 // So: using the current active transport, and the caller has asked
4040 // that its own package will be restored. In this narrow use case
4041 // we do not require the caller to hold the permission.
4042 needPermission = false;
4043 }
4044 }
4045 }
4046
4047 if (needPermission) {
4048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4049 "beginRestoreSession");
4050 } else {
4051 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4052 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004053
4054 synchronized(this) {
4055 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004056 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004057 return null;
4058 }
Chris Tate44ab8452010-11-16 15:10:49 -08004059 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004060 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004061 }
4062 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004063 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004064
Christopher Tate73a3cb32010-12-13 18:27:26 -08004065 void clearRestoreSession(ActiveRestoreSession currentSession) {
4066 synchronized(this) {
4067 if (currentSession != mActiveRestoreSession) {
4068 Slog.e(TAG, "ending non-current restore session");
4069 } else {
4070 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4071 mActiveRestoreSession = null;
4072 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4073 }
4074 }
4075 }
4076
Christopher Tate44a27902010-01-27 17:15:49 -08004077 // Note that a currently-active backup agent has notified us that it has
4078 // completed the given outstanding asynchronous backup/restore operation.
4079 public void opComplete(int token) {
4080 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004081 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004082 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4083 mCurrentOpLock.notifyAll();
4084 }
4085 }
4086
Christopher Tate9b3905c2009-06-08 15:24:01 -07004087 // ----- Restore session -----
4088
Christopher Tate80202c82010-01-25 19:37:47 -08004089 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004090 private static final String TAG = "RestoreSession";
4091
Chris Tate44ab8452010-11-16 15:10:49 -08004092 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004093 private IBackupTransport mRestoreTransport = null;
4094 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004095 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004096
Chris Tate44ab8452010-11-16 15:10:49 -08004097 ActiveRestoreSession(String packageName, String transport) {
4098 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004099 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004100 }
4101
4102 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004103 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004104 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004105 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004106 if (observer == null) {
4107 throw new IllegalArgumentException("Observer must not be null");
4108 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004109
Christopher Tate73a3cb32010-12-13 18:27:26 -08004110 if (mEnded) {
4111 throw new IllegalStateException("Restore session already ended");
4112 }
4113
Christopher Tate1bb69062010-02-19 17:02:12 -08004114 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004115 try {
Christopher Tate43383042009-07-13 15:17:13 -07004116 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004117 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004118 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004119 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004120 // spin off the transport request to our service thread
4121 mWakelock.acquire();
4122 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4123 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4124 mBackupHandler.sendMessage(msg);
4125 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004126 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004127 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004128 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004129 } finally {
4130 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004131 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004132 }
4133
Christopher Tate84725812010-02-04 15:52:40 -08004134 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004135 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4136 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004137
Chris Tate44ab8452010-11-16 15:10:49 -08004138 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004139 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004140
Christopher Tate73a3cb32010-12-13 18:27:26 -08004141 if (mEnded) {
4142 throw new IllegalStateException("Restore session already ended");
4143 }
4144
Dan Egnor0084da52009-07-29 12:57:16 -07004145 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004146 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4147 return -1;
4148 }
4149
4150 if (mPackageName != null) {
4151 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004152 return -1;
4153 }
4154
Christopher Tate21ab6a52009-09-24 18:01:46 -07004155 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004156 for (int i = 0; i < mRestoreSets.length; i++) {
4157 if (token == mRestoreSets[i].token) {
4158 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004159 mWakelock.acquire();
4160 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004161 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004162 mBackupHandler.sendMessage(msg);
4163 Binder.restoreCallingIdentity(oldId);
4164 return 0;
4165 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004166 }
4167 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004168
Joe Onorato8a9b2202010-02-26 18:56:32 -08004169 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004170 return -1;
4171 }
4172
Christopher Tate84725812010-02-04 15:52:40 -08004173 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004174 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08004175
Christopher Tate73a3cb32010-12-13 18:27:26 -08004176 if (mEnded) {
4177 throw new IllegalStateException("Restore session already ended");
4178 }
4179
Chris Tate44ab8452010-11-16 15:10:49 -08004180 if (mPackageName != null) {
4181 if (! mPackageName.equals(packageName)) {
4182 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
4183 + " on session for package " + mPackageName);
4184 return -1;
4185 }
4186 }
4187
Christopher Tate84725812010-02-04 15:52:40 -08004188 PackageInfo app = null;
4189 try {
4190 app = mPackageManager.getPackageInfo(packageName, 0);
4191 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004192 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004193 return -1;
4194 }
4195
4196 // If the caller is not privileged and is not coming from the target
4197 // app's uid, throw a permission exception back to the caller.
4198 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
4199 Binder.getCallingPid(), Binder.getCallingUid());
4200 if ((perm == PackageManager.PERMISSION_DENIED) &&
4201 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004202 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08004203 + " or calling uid=" + Binder.getCallingUid());
4204 throw new SecurityException("No permission to restore other packages");
4205 }
4206
Christopher Tate7d411a32010-02-26 11:27:08 -08004207 // If the package has no backup agent, we obviously cannot proceed
4208 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004209 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08004210 return -1;
4211 }
4212
Christopher Tate84725812010-02-04 15:52:40 -08004213 // So far so good; we're allowed to try to restore this package. Now
4214 // check whether there is data for it in the current dataset, falling back
4215 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08004216 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004217
4218 // If we didn't come up with a place to look -- no ancestral dataset and
4219 // the app has never been backed up from this device -- there's nothing
4220 // to do but return failure.
4221 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08004222 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08004223 return -1;
4224 }
4225
4226 // Ready to go: enqueue the restore request and claim success
4227 long oldId = Binder.clearCallingIdentity();
4228 mWakelock.acquire();
4229 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004230 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08004231 mBackupHandler.sendMessage(msg);
4232 Binder.restoreCallingIdentity(oldId);
4233 return 0;
4234 }
4235
Christopher Tate73a3cb32010-12-13 18:27:26 -08004236 // Posted to the handler to tear down a restore session in a cleanly synchronized way
4237 class EndRestoreRunnable implements Runnable {
4238 BackupManagerService mBackupManager;
4239 ActiveRestoreSession mSession;
4240
4241 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
4242 mBackupManager = manager;
4243 mSession = session;
4244 }
4245
4246 public void run() {
4247 // clean up the session's bookkeeping
4248 synchronized (mSession) {
4249 try {
4250 if (mSession.mRestoreTransport != null) {
4251 mSession.mRestoreTransport.finishRestore();
4252 }
4253 } catch (Exception e) {
4254 Slog.e(TAG, "Error in finishRestore", e);
4255 } finally {
4256 mSession.mRestoreTransport = null;
4257 mSession.mEnded = true;
4258 }
4259 }
4260
4261 // clean up the BackupManagerService side of the bookkeeping
4262 // and cancel any pending timeout message
4263 mBackupManager.clearRestoreSession(mSession);
4264 }
4265 }
4266
Dan Egnor0084da52009-07-29 12:57:16 -07004267 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004268 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004269
Christopher Tate73a3cb32010-12-13 18:27:26 -08004270 if (mEnded) {
4271 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07004272 }
4273
Christopher Tate73a3cb32010-12-13 18:27:26 -08004274 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07004275 }
4276 }
4277
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004278 @Override
4279 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004280 long identityToken = Binder.clearCallingIdentity();
4281 try {
4282 dumpInternal(pw);
4283 } finally {
4284 Binder.restoreCallingIdentity(identityToken);
4285 }
4286 }
4287
4288 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004289 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004290 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07004291 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08004292 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08004293 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07004294 pw.println("Last backup pass: " + mLastBackupPass
4295 + " (now = " + System.currentTimeMillis() + ')');
4296 pw.println(" next scheduled: " + mNextBackupPass);
4297
Christopher Tate91717492009-06-26 21:07:13 -07004298 pw.println("Available transports:");
4299 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004300 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
4301 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004302 IBackupTransport transport = getTransport(t);
4303 File dir = new File(mBaseStateDir, transport.transportDirName());
4304 pw.println(" destination: " + transport.currentDestinationString());
4305 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07004306 for (File f : dir.listFiles()) {
4307 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
4308 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004309 } catch (Exception e) {
4310 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004311 pw.println(" Error: " + e);
4312 }
Christopher Tate91717492009-06-26 21:07:13 -07004313 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004314
4315 pw.println("Pending init: " + mPendingInits.size());
4316 for (String s : mPendingInits) {
4317 pw.println(" " + s);
4318 }
4319
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004320 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07004321 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004322 for (int i=0; i<N; i++) {
4323 int uid = mBackupParticipants.keyAt(i);
4324 pw.print(" uid: ");
4325 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004326 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
4327 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07004328 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004329 }
4330 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004331
Christopher Tateb49ceb32010-02-08 16:22:24 -08004332 pw.println("Ancestral packages: "
4333 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07004334 if (mAncestralPackages != null) {
4335 for (String pkg : mAncestralPackages) {
4336 pw.println(" " + pkg);
4337 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08004338 }
4339
Christopher Tate73e02522009-07-15 14:18:26 -07004340 pw.println("Ever backed up: " + mEverStoredApps.size());
4341 for (String pkg : mEverStoredApps) {
4342 pw.println(" " + pkg);
4343 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004344
4345 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07004346 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07004347 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07004348 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004349 }
4350 }
Christopher Tate487529a2009-04-29 14:03:25 -07004351}