blob: e30ce72e5790db06ce7ab5c89daa84bc32cc14bf [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 Tate79ec80d2011-06-24 14:58:49 -070026import android.app.backup.BackupAgent;
Christopher Tate4a627c72011-04-01 14:43:32 -070027import android.app.backup.BackupDataOutput;
28import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060029import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070031import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070034import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.ComponentName;
Christopher Tated2c0cd42011-09-15 15:51:29 -070037import android.content.ContentResolver;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.content.Context;
39import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070041import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070042import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070043import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070044import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070045import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080046import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070047import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070048import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060049import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060050import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070051import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070052import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070053import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070054import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070055import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070056import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080057import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070058import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080059import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070060import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070061import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070062import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070063import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070064import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070065import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070066import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070068import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070069import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080070import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070071import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080072import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070073import android.util.StringBuilderPrinter;
74
Jason parksa3cdaa52011-01-13 14:15:43 -060075import com.android.internal.backup.BackupConstants;
76import com.android.internal.backup.IBackupTransport;
77import com.android.internal.backup.LocalTransport;
78import com.android.server.PackageManagerBackupAgent.Metadata;
79
Christopher Tate2efd2db2011-07-19 16:32:49 -070080import java.io.BufferedInputStream;
81import java.io.BufferedOutputStream;
82import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070083import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070084import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070085import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070086import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070087import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070088import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080089import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070090import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070091import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070092import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070093import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070094import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070095import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070096import java.security.InvalidAlgorithmParameterException;
97import java.security.InvalidKeyException;
98import java.security.Key;
99import java.security.NoSuchAlgorithmException;
100import java.security.SecureRandom;
101import java.security.spec.InvalidKeySpecException;
102import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700103import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400104import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700105import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700106import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400107import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700108import java.util.HashSet;
109import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700110import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700111import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800112import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700113import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700114import java.util.zip.Deflater;
115import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700116import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700117
Christopher Tate2efd2db2011-07-19 16:32:49 -0700118import javax.crypto.BadPaddingException;
119import javax.crypto.Cipher;
120import javax.crypto.CipherInputStream;
121import javax.crypto.CipherOutputStream;
122import javax.crypto.IllegalBlockSizeException;
123import javax.crypto.NoSuchPaddingException;
124import javax.crypto.SecretKey;
125import javax.crypto.SecretKeyFactory;
126import javax.crypto.spec.IvParameterSpec;
127import javax.crypto.spec.PBEKeySpec;
128import javax.crypto.spec.SecretKeySpec;
129
Christopher Tate487529a2009-04-29 14:03:25 -0700130class BackupManagerService extends IBackupManager.Stub {
131 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700132 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700133 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700134
135 // Name and current contents version of the full-backup manifest file
136 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
137 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700138 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
139 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700140 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate49401dd2009-07-01 12:34:29 -0700142 // How often we perform a backup pass. Privileged external callers can
143 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700144 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700145
Dan Egnorc1c49c02009-10-30 17:35:39 -0700146 // Random variation in backup scheduling time to avoid server load spikes
147 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
148
Christopher Tate8031a3d2009-07-06 16:36:05 -0700149 // The amount of time between the initial provisioning of the device and
150 // the first backup pass.
151 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
152
Christopher Tate45281862010-03-05 15:46:30 -0800153 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
154 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
155 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700156 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700157 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700158 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700159 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700160 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700161 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
162 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800163 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700164 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
165 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700166
Christopher Tate8e294d42011-08-31 20:37:12 -0700167 // backup task state machine tick
168 static final int MSG_BACKUP_RESTORE_STEP = 20;
169 static final int MSG_OP_COMPLETE = 21;
170
Christopher Tatec7b31e32009-06-10 15:49:30 -0700171 // Timeout interval for deciding that a bind or clear-data has taken too long
172 static final long TIMEOUT_INTERVAL = 10 * 1000;
173
Christopher Tate44a27902010-01-27 17:15:49 -0800174 // Timeout intervals for agent backup & restore operations
175 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700176 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700177 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800178 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
179
Christopher Tate2efd2db2011-07-19 16:32:49 -0700180 // User confirmation timeout for a full backup/restore operation. It's this long in
181 // order to give them time to enter the backup password.
182 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700183
Christopher Tate487529a2009-04-29 14:03:25 -0700184 private Context mContext;
185 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800186 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700187 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700188 private PowerManager mPowerManager;
189 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800190 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700191
Christopher Tate73e02522009-07-15 14:18:26 -0700192 boolean mEnabled; // access to this is synchronized on 'this'
193 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800194 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700195 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800196 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
197 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700198 PendingIntent mRunBackupIntent, mRunInitIntent;
199 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700200 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700201 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700202 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700203 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700204 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700205 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700206
Christopher Tatecc55f812011-08-16 16:06:53 -0700207 BackupRequest(String pkgName) {
208 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700209 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700210
211 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700212 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700213 }
Christopher Tate46758122009-05-06 11:22:00 -0700214 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800215 // Backups that we haven't started yet. Keys are package names.
216 HashMap<String,BackupRequest> mPendingBackups
217 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700218
219 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700220 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700221
222 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700223 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700224
Christopher Tate043dadc2009-06-02 16:11:00 -0700225 // The thread performing the sequence of queued backups binds to each app's agent
226 // in succession. Bind notifications are asynchronously delivered through the
227 // Activity Manager; use this lock object to signal when a requested binding has
228 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700229 final Object mAgentConnectLock = new Object();
230 IBackupAgent mConnectedAgent;
231 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700232 volatile long mLastBackupPass;
233 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700234
Christopher Tate55f931a2009-09-29 17:17:34 -0700235 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700236 final Object mClearDataLock = new Object();
237 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700238
Christopher Tate91717492009-06-26 21:07:13 -0700239 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700240 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700241 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700242 String mCurrentTransport;
243 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800244 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700245
Christopher Tate2d449afe2010-03-29 19:14:24 -0700246 class RestoreGetSetsParams {
247 public IBackupTransport transport;
248 public ActiveRestoreSession session;
249 public IRestoreObserver observer;
250
251 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
252 IRestoreObserver _observer) {
253 transport = _transport;
254 session = _session;
255 observer = _observer;
256 }
257 }
258
Christopher Tate73e02522009-07-15 14:18:26 -0700259 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700260 public IBackupTransport transport;
261 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700262 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800263 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800264 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700265 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700266 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800267
268 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700269 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800270 transport = _transport;
271 observer = _obs;
272 token = _token;
273 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800274 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700275 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700276 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800277 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700278
Chris Tate249345b2010-10-29 12:57:04 -0700279 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
280 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700281 transport = _transport;
282 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700283 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800284 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800285 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700286 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700287 filterSet = null;
288 }
289
290 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
291 String[] _filterSet, boolean _needFullBackup) {
292 transport = _transport;
293 observer = _obs;
294 token = _token;
295 pkgInfo = null;
296 pmToken = 0;
297 needFullBackup = _needFullBackup;
298 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700299 }
300 }
301
Christopher Tate73e02522009-07-15 14:18:26 -0700302 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700303 public IBackupTransport transport;
304 public PackageInfo packageInfo;
305
306 ClearParams(IBackupTransport _transport, PackageInfo _info) {
307 transport = _transport;
308 packageInfo = _info;
309 }
310 }
311
Christopher Tate4a627c72011-04-01 14:43:32 -0700312 class FullParams {
313 public ParcelFileDescriptor fd;
314 public final AtomicBoolean latch;
315 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700316 public String curPassword; // filled in by the confirmation step
317 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700318
319 FullParams() {
320 latch = new AtomicBoolean(false);
321 }
322 }
323
324 class FullBackupParams extends FullParams {
325 public boolean includeApks;
326 public boolean includeShared;
327 public boolean allApps;
328 public String[] packages;
329
330 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
331 boolean doAllApps, String[] pkgList) {
332 fd = output;
333 includeApks = saveApks;
334 includeShared = saveShared;
335 allApps = doAllApps;
336 packages = pkgList;
337 }
338 }
339
340 class FullRestoreParams extends FullParams {
341 FullRestoreParams(ParcelFileDescriptor input) {
342 fd = input;
343 }
344 }
345
Christopher Tate44a27902010-01-27 17:15:49 -0800346 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
347 // token is the index of the entry in the pending-operations list.
348 static final int OP_PENDING = 0;
349 static final int OP_ACKNOWLEDGED = 1;
350 static final int OP_TIMEOUT = -1;
351
Christopher Tate8e294d42011-08-31 20:37:12 -0700352 class Operation {
353 public int state;
354 public BackupRestoreTask callback;
355
356 Operation(int initialState, BackupRestoreTask callbackObj) {
357 state = initialState;
358 callback = callbackObj;
359 }
360 }
361 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800362 final Object mCurrentOpLock = new Object();
363 final Random mTokenGenerator = new Random();
364
Christopher Tate4a627c72011-04-01 14:43:32 -0700365 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
366
Christopher Tate5cb400b2009-06-25 16:03:14 -0700367 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700368 File mBaseStateDir;
369 File mDataDir;
370 File mJournalDir;
371 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700372
Christopher Tate2efd2db2011-07-19 16:32:49 -0700373 // Backup password, if any, and the file where it's saved. What is stored is not the
374 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
375 // persisted) salt. Validation is performed by running the challenge text through the
376 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
377 // the saved hash string, then the challenge text matches the originally supplied
378 // password text.
379 private final SecureRandom mRng = new SecureRandom();
380 private String mPasswordHash;
381 private File mPasswordHashFile;
382 private byte[] mPasswordSalt;
383
384 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
385 static final int PBKDF2_HASH_ROUNDS = 10000;
386 static final int PBKDF2_KEY_SIZE = 256; // bits
387 static final int PBKDF2_SALT_SIZE = 512; // bits
388 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
389
Christopher Tate84725812010-02-04 15:52:40 -0800390 // Keep a log of all the apps we've ever backed up, and what the
391 // dataset tokens are for both the current backup dataset and
392 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700393 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700394 HashSet<String> mEverStoredApps = new HashSet<String>();
395
Christopher Tateb49ceb32010-02-08 16:22:24 -0800396 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800397 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800398 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800399 long mAncestralToken = 0;
400 long mCurrentToken = 0;
401
Christopher Tate4cc86e12009-09-21 19:36:51 -0700402 // Persistently track the need to do a full init
403 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
404 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700405
Christopher Tate4a627c72011-04-01 14:43:32 -0700406 // Utility: build a new random integer token
407 int generateToken() {
408 int token;
409 do {
410 synchronized (mTokenGenerator) {
411 token = mTokenGenerator.nextInt();
412 }
413 } while (token < 0);
414 return token;
415 }
416
Christopher Tate44a27902010-01-27 17:15:49 -0800417 // ----- Asynchronous backup/restore handler thread -----
418
419 private class BackupHandler extends Handler {
420 public BackupHandler(Looper looper) {
421 super(looper);
422 }
423
424 public void handleMessage(Message msg) {
425
426 switch (msg.what) {
427 case MSG_RUN_BACKUP:
428 {
429 mLastBackupPass = System.currentTimeMillis();
430 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
431
432 IBackupTransport transport = getTransport(mCurrentTransport);
433 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800434 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800435 mWakelock.release();
436 break;
437 }
438
439 // snapshot the pending-backup set and work on that
440 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800441 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800442 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800443 // Do we have any work to do? Construct the work queue
444 // then release the synchronization lock to actually run
445 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800446 if (mPendingBackups.size() > 0) {
447 for (BackupRequest b: mPendingBackups.values()) {
448 queue.add(b);
449 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800450 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800451 mPendingBackups.clear();
452
453 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800454 mJournal = null;
455
Christopher Tate44a27902010-01-27 17:15:49 -0800456 }
457 }
Christopher Tatec61da312010-02-05 10:41:27 -0800458
Christopher Tate8e294d42011-08-31 20:37:12 -0700459 // At this point, we have started a new journal file, and the old
460 // file identity is being passed to the backup processing task.
461 // When it completes successfully, that old journal file will be
462 // deleted. If we crash prior to that, the old journal is parsed
463 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800464 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700465 // Spin up a backup state sequence and set it running
466 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
467 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
468 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800469 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800470 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800471 mWakelock.release();
472 }
Christopher Tate44a27902010-01-27 17:15:49 -0800473 break;
474 }
475
Christopher Tate8e294d42011-08-31 20:37:12 -0700476 case MSG_BACKUP_RESTORE_STEP:
477 {
478 try {
479 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
480 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
481 task.execute();
482 } catch (ClassCastException e) {
483 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
484 }
485 break;
486 }
487
488 case MSG_OP_COMPLETE:
489 {
490 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700491 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
492 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700493 } catch (ClassCastException e) {
494 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
495 }
496 break;
497 }
498
Christopher Tate44a27902010-01-27 17:15:49 -0800499 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700500 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700501 // TODO: refactor full backup to be a looper-based state machine
502 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700503 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700504 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
505 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700506 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tatea28e8542011-09-12 13:45:21 -0700507 params.allApps, params.packages, params.latch);
508 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800509 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700510 }
Christopher Tate44a27902010-01-27 17:15:49 -0800511
512 case MSG_RUN_RESTORE:
513 {
514 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800515 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700516 PerformRestoreTask task = new PerformRestoreTask(
517 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700518 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700519 params.needFullBackup, params.filterSet);
520 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
521 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800522 break;
523 }
524
Christopher Tate75a99702011-05-18 16:28:19 -0700525 case MSG_RUN_FULL_RESTORE:
526 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700527 // TODO: refactor full restore to be a looper-based state machine
528 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700529 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700530 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
531 params.curPassword, params.encryptPassword,
532 params.observer, params.latch);
533 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700534 break;
535 }
536
Christopher Tate44a27902010-01-27 17:15:49 -0800537 case MSG_RUN_CLEAR:
538 {
539 ClearParams params = (ClearParams)msg.obj;
540 (new PerformClearTask(params.transport, params.packageInfo)).run();
541 break;
542 }
543
544 case MSG_RUN_INITIALIZE:
545 {
546 HashSet<String> queue;
547
548 // Snapshot the pending-init queue and work on that
549 synchronized (mQueueLock) {
550 queue = new HashSet<String>(mPendingInits);
551 mPendingInits.clear();
552 }
553
554 (new PerformInitializeTask(queue)).run();
555 break;
556 }
557
Christopher Tate2d449afe2010-03-29 19:14:24 -0700558 case MSG_RUN_GET_RESTORE_SETS:
559 {
560 // Like other async operations, this is entered with the wakelock held
561 RestoreSet[] sets = null;
562 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
563 try {
564 sets = params.transport.getAvailableRestoreSets();
565 // cache the result in the active session
566 synchronized (params.session) {
567 params.session.mRestoreSets = sets;
568 }
569 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
570 } catch (Exception e) {
571 Slog.e(TAG, "Error from transport getting set list");
572 } finally {
573 if (params.observer != null) {
574 try {
575 params.observer.restoreSetsAvailable(sets);
576 } catch (RemoteException re) {
577 Slog.e(TAG, "Unable to report listing to observer");
578 } catch (Exception e) {
579 Slog.e(TAG, "Restore observer threw", e);
580 }
581 }
582
Christopher Tate2a935092011-03-03 17:30:32 -0800583 // Done: reset the session timeout clock
584 removeMessages(MSG_RESTORE_TIMEOUT);
585 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
586
Christopher Tate2d449afe2010-03-29 19:14:24 -0700587 mWakelock.release();
588 }
589 break;
590 }
591
Christopher Tate44a27902010-01-27 17:15:49 -0800592 case MSG_TIMEOUT:
593 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700594 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800595 break;
596 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800597
598 case MSG_RESTORE_TIMEOUT:
599 {
600 synchronized (BackupManagerService.this) {
601 if (mActiveRestoreSession != null) {
602 // Client app left the restore session dangling. We know that it
603 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700604 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800605 // up now.
606 Slog.w(TAG, "Restore session timed out; aborting");
607 post(mActiveRestoreSession.new EndRestoreRunnable(
608 BackupManagerService.this, mActiveRestoreSession));
609 }
610 }
611 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700612
613 case MSG_FULL_CONFIRMATION_TIMEOUT:
614 {
615 synchronized (mFullConfirmations) {
616 FullParams params = mFullConfirmations.get(msg.arg1);
617 if (params != null) {
618 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
619
620 // Release the waiter; timeout == completion
621 signalFullBackupRestoreCompletion(params);
622
623 // Remove the token from the set
624 mFullConfirmations.delete(msg.arg1);
625
626 // Report a timeout to the observer, if any
627 if (params.observer != null) {
628 try {
629 params.observer.onTimeout();
630 } catch (RemoteException e) {
631 /* don't care if the app has gone away */
632 }
633 }
634 } else {
635 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
636 }
637 }
638 break;
639 }
Christopher Tate44a27902010-01-27 17:15:49 -0800640 }
641 }
642 }
643
644 // ----- Main service implementation -----
645
Christopher Tate487529a2009-04-29 14:03:25 -0700646 public BackupManagerService(Context context) {
647 mContext = context;
648 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700649 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700650 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700651
Christopher Tateb6787f22009-07-02 17:40:45 -0700652 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
653 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
654
Christopher Tate44a27902010-01-27 17:15:49 -0800655 mBackupManagerBinder = asInterface(asBinder());
656
657 // spin up the backup/restore handler thread
658 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
659 mHandlerThread.start();
660 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
661
Christopher Tate22b87872009-05-04 16:41:53 -0700662 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700663 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700664 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700665 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700666 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800667 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800668 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800669 // If Encrypted file systems is enabled or disabled, this call will return the
670 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600671 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800672 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700673 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700674
Christopher Tate2efd2db2011-07-19 16:32:49 -0700675 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
676 if (mPasswordHashFile.exists()) {
677 FileInputStream fin = null;
678 DataInputStream in = null;
679 try {
680 fin = new FileInputStream(mPasswordHashFile);
681 in = new DataInputStream(new BufferedInputStream(fin));
682 // integer length of the salt array, followed by the salt,
683 // then the hex pw hash string
684 int saltLen = in.readInt();
685 byte[] salt = new byte[saltLen];
686 in.readFully(salt);
687 mPasswordHash = in.readUTF();
688 mPasswordSalt = salt;
689 } catch (IOException e) {
690 Slog.e(TAG, "Unable to read saved backup pw hash");
691 } finally {
692 try {
693 if (in != null) in.close();
694 if (fin != null) fin.close();
695 } catch (IOException e) {
696 Slog.w(TAG, "Unable to close streams");
697 }
698 }
699 }
700
Christopher Tate4cc86e12009-09-21 19:36:51 -0700701 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700702 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700703 IntentFilter filter = new IntentFilter();
704 filter.addAction(RUN_BACKUP_ACTION);
705 context.registerReceiver(mRunBackupReceiver, filter,
706 android.Manifest.permission.BACKUP, null);
707
708 mRunInitReceiver = new RunInitializeReceiver();
709 filter = new IntentFilter();
710 filter.addAction(RUN_INITIALIZE_ACTION);
711 context.registerReceiver(mRunInitReceiver, filter,
712 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700713
714 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700715 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
716 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
717
Christopher Tate4cc86e12009-09-21 19:36:51 -0700718 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
719 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
720 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
721
Christopher Tatecde87f42009-06-12 12:55:53 -0700722 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700723 mJournalDir = new File(mBaseStateDir, "pending");
724 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700725 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700726
Christopher Tate73e02522009-07-15 14:18:26 -0700727 // Set up the various sorts of package tracking we do
728 initPackageTracking();
729
Christopher Tateabce4e82009-06-18 18:35:32 -0700730 // Build our mapping of uid to backup client services. This implicitly
731 // schedules a backup pass on the Package Manager metadata the first
732 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700733 synchronized (mBackupParticipants) {
734 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700735 }
736
Dan Egnor87a02bc2009-06-17 02:30:10 -0700737 // Set up our transport options and initialize the default transport
738 // TODO: Have transports register themselves somehow?
739 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700740 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700741 ComponentName localName = new ComponentName(context, LocalTransport.class);
742 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700743
Christopher Tate91717492009-06-26 21:07:13 -0700744 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700745 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
746 Settings.Secure.BACKUP_TRANSPORT);
747 if ("".equals(mCurrentTransport)) {
748 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700749 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800750 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700751
752 // Attach to the Google backup transport. When this comes up, it will set
753 // itself as the current transport because we explicitly reset mCurrentTransport
754 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700755 ComponentName transportComponent = new ComponentName("com.google.android.backup",
756 "com.google.android.backup.BackupTransportService");
757 try {
758 // If there's something out there that is supposed to be the Google
759 // backup transport, make sure it's legitimately part of the OS build
760 // and not an app lying about its package name.
761 ApplicationInfo info = mPackageManager.getApplicationInfo(
762 transportComponent.getPackageName(), 0);
763 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
764 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
765 Intent intent = new Intent().setComponent(transportComponent);
766 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
767 } else {
768 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
769 }
770 } catch (PackageManager.NameNotFoundException nnf) {
771 // No such package? No binding.
772 if (DEBUG) Slog.v(TAG, "Google transport not present");
773 }
Christopher Tateaa088442009-06-16 18:25:46 -0700774
Christopher Tatecde87f42009-06-12 12:55:53 -0700775 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700776 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700777 parseLeftoverJournals();
778
Christopher Tateb6787f22009-07-02 17:40:45 -0700779 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700780 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700781
782 // Start the backup passes going
783 setBackupEnabled(areEnabled);
784 }
785
786 private class RunBackupReceiver extends BroadcastReceiver {
787 public void onReceive(Context context, Intent intent) {
788 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700789 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700790 if (mPendingInits.size() > 0) {
791 // If there are pending init operations, we process those
792 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800793 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700794 try {
795 mAlarmManager.cancel(mRunInitIntent);
796 mRunInitIntent.send();
797 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800798 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700799 // can't really do more than bail here
800 }
801 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800802 // Don't run backups now if we're disabled or not yet
803 // fully set up.
804 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800805 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700806
807 // Acquire the wakelock and pass it to the backup thread. it will
808 // be released once backup concludes.
809 mWakelock.acquire();
810
811 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
812 mBackupHandler.sendMessage(msg);
813 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800814 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700815 }
816 }
817 }
818 }
819 }
820 }
821
822 private class RunInitializeReceiver extends BroadcastReceiver {
823 public void onReceive(Context context, Intent intent) {
824 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
825 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800826 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700827
828 // Acquire the wakelock and pass it to the init thread. it will
829 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700830 mWakelock.acquire();
831
Christopher Tate4cc86e12009-09-21 19:36:51 -0700832 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700833 mBackupHandler.sendMessage(msg);
834 }
835 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700836 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700837 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700838
Christopher Tate73e02522009-07-15 14:18:26 -0700839 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800840 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700841
Christopher Tate84725812010-02-04 15:52:40 -0800842 // Remember our ancestral dataset
843 mTokenFile = new File(mBaseStateDir, "ancestral");
844 try {
845 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800846 int version = tf.readInt();
847 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
848 mAncestralToken = tf.readLong();
849 mCurrentToken = tf.readLong();
850
851 int numPackages = tf.readInt();
852 if (numPackages >= 0) {
853 mAncestralPackages = new HashSet<String>();
854 for (int i = 0; i < numPackages; i++) {
855 String pkgName = tf.readUTF();
856 mAncestralPackages.add(pkgName);
857 }
858 }
859 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800860 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800861 } catch (FileNotFoundException fnf) {
862 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800864 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800866 }
867
Christopher Tatee97e8072009-07-15 16:45:50 -0700868 // Keep a log of what apps we've ever backed up. Because we might have
869 // rebooted in the middle of an operation that was removing something from
870 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700871 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700872 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700873
Christopher Tatee97e8072009-07-15 16:45:50 -0700874 // If we were in the middle of removing something from the ever-backed-up
875 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700876 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700877 if (tempProcessedFile.exists()) {
878 tempProcessedFile.delete();
879 }
880
Dan Egnor852f8e42009-09-30 11:20:45 -0700881 // If there are previous contents, parse them out then start a new
882 // file to continue the recordkeeping.
883 if (mEverStored.exists()) {
884 RandomAccessFile temp = null;
885 RandomAccessFile in = null;
886
887 try {
888 temp = new RandomAccessFile(tempProcessedFile, "rws");
889 in = new RandomAccessFile(mEverStored, "r");
890
891 while (true) {
892 PackageInfo info;
893 String pkg = in.readUTF();
894 try {
895 info = mPackageManager.getPackageInfo(pkg, 0);
896 mEverStoredApps.add(pkg);
897 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700898 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700899 } catch (NameNotFoundException e) {
900 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700901 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700902 }
903 }
904 } catch (EOFException e) {
905 // Once we've rewritten the backup history log, atomically replace the
906 // old one with the new one then reopen the file for continuing use.
907 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700909 }
910 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800911 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700912 } finally {
913 try { if (temp != null) temp.close(); } catch (IOException e) {}
914 try { if (in != null) in.close(); } catch (IOException e) {}
915 }
916 }
917
Christopher Tate73e02522009-07-15 14:18:26 -0700918 // Register for broadcasts about package install, etc., so we can
919 // update the provider list.
920 IntentFilter filter = new IntentFilter();
921 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
922 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700923 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700924 filter.addDataScheme("package");
925 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800926 // Register for events related to sdcard installation.
927 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800928 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
929 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800930 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700931 }
932
Christopher Tatecde87f42009-06-12 12:55:53 -0700933 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700934 for (File f : mJournalDir.listFiles()) {
935 if (mJournal == null || f.compareTo(mJournal) != 0) {
936 // This isn't the current journal, so it must be a leftover. Read
937 // out the package names mentioned there and schedule them for
938 // backup.
939 RandomAccessFile in = null;
940 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400941 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700942 in = new RandomAccessFile(f, "r");
943 while (true) {
944 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400945 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700946 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700947 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700948 } catch (EOFException e) {
949 // no more data; we're done
950 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800951 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700952 } finally {
953 // close/delete the file
954 try { if (in != null) in.close(); } catch (IOException e) {}
955 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700956 }
957 }
958 }
959 }
960
Christopher Tate2efd2db2011-07-19 16:32:49 -0700961 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
962 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
963 }
964
965 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
966 try {
967 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
968 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
969 return keyFactory.generateSecret(ks);
970 } catch (InvalidKeySpecException e) {
971 Slog.e(TAG, "Invalid key spec for PBKDF2!");
972 } catch (NoSuchAlgorithmException e) {
973 Slog.e(TAG, "PBKDF2 unavailable!");
974 }
975 return null;
976 }
977
978 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
979 SecretKey key = buildPasswordKey(pw, salt, rounds);
980 if (key != null) {
981 return byteArrayToHex(key.getEncoded());
982 }
983 return null;
984 }
985
986 private String byteArrayToHex(byte[] data) {
987 StringBuilder buf = new StringBuilder(data.length * 2);
988 for (int i = 0; i < data.length; i++) {
989 buf.append(Byte.toHexString(data[i], true));
990 }
991 return buf.toString();
992 }
993
994 private byte[] hexToByteArray(String digits) {
995 final int bytes = digits.length() / 2;
996 if (2*bytes != digits.length()) {
997 throw new IllegalArgumentException("Hex string must have an even number of digits");
998 }
999
1000 byte[] result = new byte[bytes];
1001 for (int i = 0; i < digits.length(); i += 2) {
1002 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1003 }
1004 return result;
1005 }
1006
1007 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1008 char[] mkAsChar = new char[pwBytes.length];
1009 for (int i = 0; i < pwBytes.length; i++) {
1010 mkAsChar[i] = (char) pwBytes[i];
1011 }
1012
1013 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1014 return checksum.getEncoded();
1015 }
1016
1017 // Used for generating random salts or passwords
1018 private byte[] randomBytes(int bits) {
1019 byte[] array = new byte[bits / 8];
1020 mRng.nextBytes(array);
1021 return array;
1022 }
1023
1024 // Backup password management
1025 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1026 if (mPasswordHash == null) {
1027 // no current password case -- require that 'currentPw' be null or empty
1028 if (candidatePw == null || "".equals(candidatePw)) {
1029 return true;
1030 } // else the non-empty candidate does not match the empty stored pw
1031 } else {
1032 // hash the stated current pw and compare to the stored one
1033 if (candidatePw != null && candidatePw.length() > 0) {
1034 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1035 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1036 // candidate hash matches the stored hash -- the password matches
1037 return true;
1038 }
1039 } // else the stored pw is nonempty but the candidate is empty; no match
1040 }
1041 return false;
1042 }
1043
1044 @Override
1045 public boolean setBackupPassword(String currentPw, String newPw) {
1046 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1047 "setBackupPassword");
1048
1049 // If the supplied pw doesn't hash to the the saved one, fail
1050 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1051 return false;
1052 }
1053
1054 // Clearing the password is okay
1055 if (newPw == null || newPw.isEmpty()) {
1056 if (mPasswordHashFile.exists()) {
1057 if (!mPasswordHashFile.delete()) {
1058 // Unable to delete the old pw file, so fail
1059 Slog.e(TAG, "Unable to clear backup password");
1060 return false;
1061 }
1062 }
1063 mPasswordHash = null;
1064 mPasswordSalt = null;
1065 return true;
1066 }
1067
1068 try {
1069 // Okay, build the hash of the new backup password
1070 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1071 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1072
1073 OutputStream pwf = null, buffer = null;
1074 DataOutputStream out = null;
1075 try {
1076 pwf = new FileOutputStream(mPasswordHashFile);
1077 buffer = new BufferedOutputStream(pwf);
1078 out = new DataOutputStream(buffer);
1079 // integer length of the salt array, followed by the salt,
1080 // then the hex pw hash string
1081 out.writeInt(salt.length);
1082 out.write(salt);
1083 out.writeUTF(newPwHash);
1084 out.flush();
1085 mPasswordHash = newPwHash;
1086 mPasswordSalt = salt;
1087 return true;
1088 } finally {
1089 if (out != null) out.close();
1090 if (buffer != null) buffer.close();
1091 if (pwf != null) pwf.close();
1092 }
1093 } catch (IOException e) {
1094 Slog.e(TAG, "Unable to set backup password");
1095 }
1096 return false;
1097 }
1098
1099 @Override
1100 public boolean hasBackupPassword() {
1101 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1102 "hasBackupPassword");
1103 return (mPasswordHash != null && mPasswordHash.length() > 0);
1104 }
1105
Christopher Tate4cc86e12009-09-21 19:36:51 -07001106 // Maintain persistent state around whether need to do an initialize operation.
1107 // Must be called with the queue lock held.
1108 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001109 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001110 + " on transport " + transportName);
1111 try {
1112 IBackupTransport transport = getTransport(transportName);
1113 String transportDirName = transport.transportDirName();
1114 File stateDir = new File(mBaseStateDir, transportDirName);
1115 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1116
1117 if (isPending) {
1118 // We need an init before we can proceed with sending backup data.
1119 // Record that with an entry in our set of pending inits, as well as
1120 // journaling it via creation of a sentinel file.
1121 mPendingInits.add(transportName);
1122 try {
1123 (new FileOutputStream(initPendingFile)).close();
1124 } catch (IOException ioe) {
1125 // Something is badly wrong with our permissions; just try to move on
1126 }
1127 } else {
1128 // No more initialization needed; wipe the journal and reset our state.
1129 initPendingFile.delete();
1130 mPendingInits.remove(transportName);
1131 }
1132 } catch (RemoteException e) {
1133 // can't happen; the transport is local
1134 }
1135 }
1136
Christopher Tated55e18a2009-09-21 10:12:59 -07001137 // Reset all of our bookkeeping, in response to having been told that
1138 // the backend data has been wiped [due to idle expiry, for example],
1139 // so we must re-upload all saved settings.
1140 void resetBackupState(File stateFileDir) {
1141 synchronized (mQueueLock) {
1142 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001143 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001144 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001145
Christopher Tate84725812010-02-04 15:52:40 -08001146 mCurrentToken = 0;
1147 writeRestoreTokens();
1148
Christopher Tated55e18a2009-09-21 10:12:59 -07001149 // Remove all the state files
1150 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001151 // ... but don't touch the needs-init sentinel
1152 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1153 sf.delete();
1154 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001155 }
Christopher Tate45597642011-04-04 16:59:21 -07001156 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001157
Christopher Tate45597642011-04-04 16:59:21 -07001158 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001159 synchronized (mBackupParticipants) {
1160 int N = mBackupParticipants.size();
1161 for (int i=0; i<N; i++) {
1162 int uid = mBackupParticipants.keyAt(i);
1163 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1164 for (ApplicationInfo app: participants) {
1165 dataChangedImpl(app.packageName);
1166 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001167 }
1168 }
1169 }
1170
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001171 // Add a transport to our set of available backends. If 'transport' is null, this
1172 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001173 private void registerTransport(String name, IBackupTransport transport) {
1174 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001175 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001176 if (transport != null) {
1177 mTransports.put(name, transport);
1178 } else {
1179 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001180 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001181 mCurrentTransport = null;
1182 }
1183 // Nothing further to do in the unregistration case
1184 return;
1185 }
Christopher Tate91717492009-06-26 21:07:13 -07001186 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001187
1188 // If the init sentinel file exists, we need to be sure to perform the init
1189 // as soon as practical. We also create the state directory at registration
1190 // time to ensure it's present from the outset.
1191 try {
1192 String transportName = transport.transportDirName();
1193 File stateDir = new File(mBaseStateDir, transportName);
1194 stateDir.mkdirs();
1195
1196 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1197 if (initSentinel.exists()) {
1198 synchronized (mQueueLock) {
1199 mPendingInits.add(transportName);
1200
1201 // TODO: pick a better starting time than now + 1 minute
1202 long delay = 1000 * 60; // one minute, in milliseconds
1203 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1204 System.currentTimeMillis() + delay, mRunInitIntent);
1205 }
1206 }
1207 } catch (RemoteException e) {
1208 // can't happen, the transport is local
1209 }
Christopher Tate91717492009-06-26 21:07:13 -07001210 }
1211
Christopher Tate3799bc22009-05-06 16:13:56 -07001212 // ----- Track installation/removal of packages -----
1213 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1214 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001215 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001216
Christopher Tate3799bc22009-05-06 16:13:56 -07001217 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001218 boolean replacing = false;
1219 boolean added = false;
1220 Bundle extras = intent.getExtras();
1221 String pkgList[] = null;
1222 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001223 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1224 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001225 Uri uri = intent.getData();
1226 if (uri == null) {
1227 return;
1228 }
1229 String pkgName = uri.getSchemeSpecificPart();
1230 if (pkgName != null) {
1231 pkgList = new String[] { pkgName };
1232 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001233 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1234 // use the existing "add with replacement" logic
1235 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1236 added = replacing = true;
1237 } else {
1238 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1239 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1240 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001241 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001242 added = true;
1243 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001244 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001245 added = false;
1246 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1247 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001248
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001249 if (pkgList == null || pkgList.length == 0) {
1250 return;
1251 }
1252 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001253 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001254 for (String pkgName : pkgList) {
1255 if (replacing) {
1256 // The package was just upgraded
1257 updatePackageParticipantsLocked(pkgName);
1258 } else {
1259 // The package was just added
1260 addPackageParticipantsLocked(pkgName);
1261 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001262 }
1263 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001264 } else {
1265 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001266 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1267 } else {
1268 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001269 for (String pkgName : pkgList) {
1270 removePackageParticipantsLocked(pkgName);
1271 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001272 }
1273 }
1274 }
1275 }
1276 };
1277
Dan Egnor87a02bc2009-06-17 02:30:10 -07001278 // ----- Track connection to GoogleBackupTransport service -----
1279 ServiceConnection mGoogleConnection = new ServiceConnection() {
1280 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001281 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001282 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001283 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001284 }
1285
1286 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001287 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001288 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001289 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001290 }
1291 };
1292
Christopher Tate181fafa2009-05-14 11:12:14 -07001293 // Add the backup agents in the given package to our set of known backup participants.
1294 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001295 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001296 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001297 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001298 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001299 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001300 }
1301
Christopher Tate181fafa2009-05-14 11:12:14 -07001302 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001303 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001304 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001305 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001306 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001307 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001308 + " uid=" + p.applicationInfo.uid
1309 + " killAfterRestore="
1310 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001311 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001312 }
1313 }
1314
Dan Egnorefe52642009-06-24 00:16:33 -07001315 for (PackageInfo pkg : targetPkgs) {
1316 if (packageName == null || pkg.packageName.equals(packageName)) {
1317 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001318 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001319 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001320 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001321 mBackupParticipants.put(uid, set);
1322 }
Dan Egnorefe52642009-06-24 00:16:33 -07001323 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001324
1325 // If we've never seen this app before, schedule a backup for it
1326 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001327 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001328 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001329 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001330 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001331 }
Christopher Tate487529a2009-04-29 14:03:25 -07001332 }
1333 }
1334
Christopher Tate6785dd82009-06-18 15:58:25 -07001335 // Remove the given package's entry from our known active set. If
1336 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001337 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001338 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001339 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001340 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001341 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001342 } else {
1343 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001344 List<PackageInfo> knownPackages = allAgentPackages();
1345 for (PackageInfo pkg : knownPackages) {
1346 allApps.add(pkg.packageName);
1347 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001348 }
1349 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001350 }
1351
Joe Onorato8ad02812009-05-13 01:41:44 -04001352 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001353 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001354 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001355 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001356 + ") removing " + allPackageNames.size() + " entries");
1357 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001358 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001359 }
1360 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001361 for (String pkg : allPackageNames) {
1362 if (packageName == null || pkg.equals(packageName)) {
1363 int uid = -1;
1364 try {
1365 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1366 uid = info.applicationInfo.uid;
1367 } catch (NameNotFoundException e) {
1368 // we don't know this package name, so just skip it for now
1369 continue;
1370 }
1371
Christopher Tate181fafa2009-05-14 11:12:14 -07001372 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001373 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001374 // Find the existing entry with the same package name, and remove it.
1375 // We can't just remove(app) because the instances are different.
1376 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001377 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001378 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001379 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001380 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001381 break;
1382 }
1383 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001384 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001385 mBackupParticipants.delete(uid);
1386 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001387 }
1388 }
1389 }
1390 }
1391
Christopher Tate181fafa2009-05-14 11:12:14 -07001392 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001393 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001394 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001395 int flags = PackageManager.GET_SIGNATURES;
1396 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1397 int N = packages.size();
1398 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001399 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001400 try {
1401 ApplicationInfo app = pkg.applicationInfo;
1402 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001403 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001404 packages.remove(a);
1405 }
1406 else {
1407 // we will need the shared library path, so look that up and store it here
1408 app = mPackageManager.getApplicationInfo(pkg.packageName,
1409 PackageManager.GET_SHARED_LIBRARY_FILES);
1410 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1411 }
1412 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001413 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001414 }
1415 }
Dan Egnorefe52642009-06-24 00:16:33 -07001416 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001417 }
Christopher Tateaa088442009-06-16 18:25:46 -07001418
Christopher Tate3799bc22009-05-06 16:13:56 -07001419 // Reset the given package's known backup participants. Unlike add/remove, the update
1420 // action cannot be passed a null package name.
1421 void updatePackageParticipantsLocked(String packageName) {
1422 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001423 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001424 return;
1425 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001426 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001427
1428 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001429 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001430 List<String> allAppNames = new ArrayList<String>();
1431 for (PackageInfo pkg : allApps) {
1432 allAppNames.add(pkg.packageName);
1433 }
1434 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001435 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001436 }
1437
Christopher Tate84725812010-02-04 15:52:40 -08001438 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001439 // backed up at least once
1440 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001441 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1442
1443 synchronized (mEverStoredApps) {
1444 if (!mEverStoredApps.add(packageName)) return;
1445
1446 RandomAccessFile out = null;
1447 try {
1448 out = new RandomAccessFile(mEverStored, "rws");
1449 out.seek(out.length());
1450 out.writeUTF(packageName);
1451 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001452 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001453 } finally {
1454 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001455 }
1456 }
1457 }
1458
Christopher Tatee97e8072009-07-15 16:45:50 -07001459 // Remove our awareness of having ever backed up the given package
1460 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001461 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1462 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001463
Dan Egnor852f8e42009-09-30 11:20:45 -07001464 synchronized (mEverStoredApps) {
1465 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1466 // we'll recognize on initialization time that the package no longer
1467 // exists and fix it up then.
1468 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1469 RandomAccessFile known = null;
1470 try {
1471 known = new RandomAccessFile(tempKnownFile, "rws");
1472 mEverStoredApps.remove(packageName);
1473 for (String s : mEverStoredApps) {
1474 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001475 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001476 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001477 known.close();
1478 known = null;
1479 if (!tempKnownFile.renameTo(mEverStored)) {
1480 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1481 }
1482 } catch (IOException e) {
1483 // Bad: we couldn't create the new copy. For safety's sake we
1484 // abandon the whole process and remove all what's-backed-up
1485 // state entirely, meaning we'll force a backup pass for every
1486 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001487 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001488 mEverStoredApps.clear();
1489 tempKnownFile.delete();
1490 mEverStored.delete();
1491 } finally {
1492 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001493 }
1494 }
1495 }
1496
Christopher Tateb49ceb32010-02-08 16:22:24 -08001497 // Persistently record the current and ancestral backup tokens as well
1498 // as the set of packages with data [supposedly] available in the
1499 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001500 void writeRestoreTokens() {
1501 try {
1502 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001503
1504 // First, the version number of this record, for futureproofing
1505 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1506
1507 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001508 af.writeLong(mAncestralToken);
1509 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001510
1511 // Now write the set of ancestral packages
1512 if (mAncestralPackages == null) {
1513 af.writeInt(-1);
1514 } else {
1515 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001516 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001517 for (String pkgName : mAncestralPackages) {
1518 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001519 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001520 }
1521 }
Christopher Tate84725812010-02-04 15:52:40 -08001522 af.close();
1523 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001525 }
1526 }
1527
Dan Egnor87a02bc2009-06-17 02:30:10 -07001528 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001529 private IBackupTransport getTransport(String transportName) {
1530 synchronized (mTransports) {
1531 IBackupTransport transport = mTransports.get(transportName);
1532 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001533 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001534 }
1535 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001536 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001537 }
1538
Christopher Tatedf01dea2009-06-09 20:45:02 -07001539 // fire off a backup agent, blocking until it attaches or times out
1540 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1541 IBackupAgent agent = null;
1542 synchronized(mAgentConnectLock) {
1543 mConnecting = true;
1544 mConnectedAgent = null;
1545 try {
1546 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001547 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001548
1549 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001550 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001551 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1552 while (mConnecting && mConnectedAgent == null
1553 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001554 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001557 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001558 return null;
1559 }
1560 }
1561
1562 // if we timed out with no connect, abort and move on
1563 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001564 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001565 return null;
1566 }
1567 agent = mConnectedAgent;
1568 }
1569 } catch (RemoteException e) {
1570 // can't happen
1571 }
1572 }
1573 return agent;
1574 }
1575
Christopher Tatec7b31e32009-06-10 15:49:30 -07001576 // clear an application's data, blocking until the operation completes or times out
1577 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001578 // Don't wipe packages marked allowClearUserData=false
1579 try {
1580 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1581 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001582 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001583 + packageName);
1584 return;
1585 }
1586 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001588 return;
1589 }
1590
Christopher Tatec7b31e32009-06-10 15:49:30 -07001591 ClearDataObserver observer = new ClearDataObserver();
1592
1593 synchronized(mClearDataLock) {
1594 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001595 try {
1596 mActivityManager.clearApplicationUserData(packageName, observer);
1597 } catch (RemoteException e) {
1598 // can't happen because the activity manager is in this process
1599 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001600
1601 // only wait 10 seconds for the clear data to happen
1602 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1603 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1604 try {
1605 mClearDataLock.wait(5000);
1606 } catch (InterruptedException e) {
1607 // won't happen, but still.
1608 mClearingData = false;
1609 }
1610 }
1611 }
1612 }
1613
1614 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001615 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001616 synchronized(mClearDataLock) {
1617 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001618 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001619 }
1620 }
1621 }
1622
Christopher Tate1bb69062010-02-19 17:02:12 -08001623 // Get the restore-set token for the best-available restore set for this package:
1624 // the active set if possible, else the ancestral one. Returns zero if none available.
1625 long getAvailableRestoreToken(String packageName) {
1626 long token = mAncestralToken;
1627 synchronized (mQueueLock) {
1628 if (mEverStoredApps.contains(packageName)) {
1629 token = mCurrentToken;
1630 }
1631 }
1632 return token;
1633 }
1634
Christopher Tate44a27902010-01-27 17:15:49 -08001635 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001636 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1637
1638 interface BackupRestoreTask {
1639 // Execute one tick of whatever state machine the task implements
1640 void execute();
1641
1642 // An operation that wanted a callback has completed
1643 void operationComplete();
1644
1645 // An operation that wanted a callback has timed out
1646 void handleTimeout();
1647 }
1648
1649 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1650 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1651 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001652 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001653 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1654
1655 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1656 mBackupHandler.sendMessageDelayed(msg, interval);
1657 }
1658 }
1659
1660 // synchronous waiter case
1661 boolean waitUntilOperationComplete(int token) {
1662 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1663 + Integer.toHexString(token));
1664 int finalState = OP_PENDING;
1665 Operation op = null;
1666 synchronized (mCurrentOpLock) {
1667 while (true) {
1668 op = mCurrentOperations.get(token);
1669 if (op == null) {
1670 // mysterious disappearance: treat as success with no callback
1671 break;
1672 } else {
1673 if (op.state == OP_PENDING) {
1674 try {
1675 mCurrentOpLock.wait();
1676 } catch (InterruptedException e) {}
1677 // When the wait is notified we loop around and recheck the current state
1678 } else {
1679 // No longer pending; we're done
1680 finalState = op.state;
1681 break;
1682 }
Christopher Tate44a27902010-01-27 17:15:49 -08001683 }
Christopher Tate44a27902010-01-27 17:15:49 -08001684 }
1685 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001686
Christopher Tate44a27902010-01-27 17:15:49 -08001687 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001688 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001689 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001690 return finalState == OP_ACKNOWLEDGED;
1691 }
1692
Christopher Tate8e294d42011-08-31 20:37:12 -07001693 void handleTimeout(int token, Object obj) {
1694 // Notify any synchronous waiters
1695 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001696 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001697 op = mCurrentOperations.get(token);
1698 if (MORE_DEBUG) {
1699 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1700 + " but no op found");
1701 }
1702 int state = (op != null) ? op.state : OP_TIMEOUT;
1703 if (state == OP_PENDING) {
1704 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1705 op.state = OP_TIMEOUT;
1706 mCurrentOperations.put(token, op);
1707 }
1708 mCurrentOpLock.notifyAll();
1709 }
1710
1711 // If there's a TimeoutHandler for this event, call it
1712 if (op != null && op.callback != null) {
1713 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001714 }
Christopher Tate44a27902010-01-27 17:15:49 -08001715 }
1716
Christopher Tate043dadc2009-06-02 16:11:00 -07001717 // ----- Back up a set of applications via a worker thread -----
1718
Christopher Tate8e294d42011-08-31 20:37:12 -07001719 enum BackupState {
1720 INITIAL,
1721 RUNNING_QUEUE,
1722 FINAL
1723 }
1724
1725 class PerformBackupTask implements BackupRestoreTask {
1726 private static final String TAG = "PerformBackupTask";
1727
Christopher Tateaa088442009-06-16 18:25:46 -07001728 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001729 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001730 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001731 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001732 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001733 BackupState mCurrentState;
1734
1735 // carried information about the current in-flight operation
1736 PackageInfo mCurrentPackage;
1737 File mSavedStateName;
1738 File mBackupDataName;
1739 File mNewStateName;
1740 ParcelFileDescriptor mSavedState;
1741 ParcelFileDescriptor mBackupData;
1742 ParcelFileDescriptor mNewState;
1743 int mStatus;
1744 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001745
Christopher Tate44a27902010-01-27 17:15:49 -08001746 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001747 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001748 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001749 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001750 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001751
1752 try {
1753 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1754 } catch (RemoteException e) {
1755 // can't happen; the transport is local
1756 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001757
1758 mCurrentState = BackupState.INITIAL;
1759 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001760 }
1761
Christopher Tate8e294d42011-08-31 20:37:12 -07001762 // Main entry point: perform one chunk of work, updating the state as appropriate
1763 // and reposting the next chunk to the primary backup handler thread.
1764 @Override
1765 public void execute() {
1766 switch (mCurrentState) {
1767 case INITIAL:
1768 beginBackup();
1769 break;
1770
1771 case RUNNING_QUEUE:
1772 invokeNextAgent();
1773 break;
1774
1775 case FINAL:
1776 if (!mFinished) finalizeBackup();
1777 else {
1778 Slog.e(TAG, "Duplicate finish");
1779 }
Christopher Tate2982d062011-09-06 20:35:24 -07001780 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001781 break;
1782 }
1783 }
1784
1785 // We're starting a backup pass. Initialize the transport and send
1786 // the PM metadata blob if we haven't already.
1787 void beginBackup() {
1788 mStatus = BackupConstants.TRANSPORT_OK;
1789
1790 // Sanity check: if the queue is empty we have no work to do.
1791 if (mOriginalQueue.isEmpty()) {
1792 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1793 return;
1794 }
1795
1796 // We need to retain the original queue contents in case of transport
1797 // failure, but we want a working copy that we can manipulate along
1798 // the way.
1799 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1800
Joe Onorato8a9b2202010-02-26 18:56:32 -08001801 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001802
Christopher Tate8e294d42011-08-31 20:37:12 -07001803 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001804 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001805 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001806
Dan Egnor852f8e42009-09-30 11:20:45 -07001807 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001808 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001810 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001811 mStatus = mTransport.initializeDevice();
1812 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001813 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001814 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001815 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001816 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001817 }
Dan Egnor01445162009-09-21 17:04:05 -07001818 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001819
1820 // The package manager doesn't have a proper <application> etc, but since
1821 // it's running here in the system process we can just set up its agent
1822 // directly and use a synthetic BackupRequest. We always run this pass
1823 // because it's cheap and this way we guarantee that we don't get out of
1824 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001825 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001826 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1827 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001828 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001829 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1830 }
Christopher Tate90967f42009-09-20 15:28:33 -07001831
Christopher Tate8e294d42011-08-31 20:37:12 -07001832 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1833 // The backend reports that our dataset has been wiped. Note this in
1834 // the event log; the no-success code below will reset the backup
1835 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001836 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001837 }
1838 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001840 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001841 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001842 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1843 // metadata and its completion/timeout callback will continue the state
1844 // machine chain. If it failed that won't happen; we handle that now.
1845 if (mStatus != BackupConstants.TRANSPORT_OK) {
1846 // if things went wrong at this point, we need to
1847 // restage everything and try again later.
1848 resetBackupState(mStateDir); // Just to make sure.
1849 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001850 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001851 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001852 }
1853
Christopher Tate8e294d42011-08-31 20:37:12 -07001854 // Transport has been initialized and the PM metadata submitted successfully
1855 // if that was warranted. Now we process the single next thing in the queue.
1856 void invokeNextAgent() {
1857 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001858
Christopher Tate8e294d42011-08-31 20:37:12 -07001859 // Sanity check that we have work to do. If not, skip to the end where
1860 // we reestablish the wakelock invariants etc.
1861 if (mQueue.isEmpty()) {
1862 Slog.e(TAG, "Running queue but it's empty!");
1863 executeNextState(BackupState.FINAL);
1864 return;
1865 }
1866
1867 // pop the entry we're going to process on this step
1868 BackupRequest request = mQueue.get(0);
1869 mQueue.remove(0);
1870
1871 Slog.d(TAG, "starting agent for backup of " + request);
1872
1873 // Verify that the requested app exists; it might be something that
1874 // requested a backup but was then uninstalled. The request was
1875 // journalled and rather than tamper with the journal it's safer
1876 // to sanity-check here. This also gives us the classname of the
1877 // package's backup agent.
1878 try {
1879 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1880 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001881
Christopher Tate043dadc2009-06-02 16:11:00 -07001882 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001883 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001884 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1885 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001886 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001887 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001888 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1889 // at this point we'll either get a completion callback from the
1890 // agent, or a timeout message on the main handler. either way, we're
1891 // done here as long as we're successful so far.
1892 } else {
1893 // Timeout waiting for the agent
1894 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001895 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001896 } catch (SecurityException ex) {
1897 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001898 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001899 mStatus = BackupConstants.AGENT_ERROR;
1900 }
1901 } catch (NameNotFoundException e) {
1902 Slog.d(TAG, "Package does not exist; skipping");
1903 } finally {
1904 mWakelock.setWorkSource(null);
1905
1906 // If there was an agent error, no timeout/completion handling will occur.
1907 // That means we need to deal with the next state ourselves.
1908 if (mStatus != BackupConstants.TRANSPORT_OK) {
1909 BackupState nextState = BackupState.RUNNING_QUEUE;
1910
1911 // An agent-level failure means we reenqueue this one agent for
1912 // a later retry, but otherwise proceed normally.
1913 if (mStatus == BackupConstants.AGENT_ERROR) {
1914 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1915 + " - restaging");
1916 dataChangedImpl(request.packageName);
1917 mStatus = BackupConstants.TRANSPORT_OK;
1918 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1919 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1920 // Transport-level failure means we reenqueue everything
1921 revertAndEndBackup();
1922 nextState = BackupState.FINAL;
1923 }
1924
1925 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001926 }
1927 }
1928 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001929
Christopher Tate8e294d42011-08-31 20:37:12 -07001930 void finalizeBackup() {
1931 // Either backup was successful, in which case we of course do not need
1932 // this pass's journal any more; or it failed, in which case we just
1933 // re-enqueued all of these packages in the current active journal.
1934 // Either way, we no longer need this pass's journal.
1935 if (mJournal != null && !mJournal.delete()) {
1936 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1937 }
1938
1939 // If everything actually went through and this is the first time we've
1940 // done a backup, we can now record what the current backup dataset token
1941 // is.
1942 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1943 try {
1944 mCurrentToken = mTransport.getCurrentRestoreSet();
1945 } catch (RemoteException e) {} // can't happen
1946 writeRestoreTokens();
1947 }
1948
1949 // Set up the next backup pass
1950 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1951 backupNow();
1952 }
1953
1954 // Only once we're entirely finished do we release the wakelock
1955 Slog.i(TAG, "Backup pass finished.");
1956 mWakelock.release();
1957 }
1958
1959 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1960 // handler in case it doesn't get back to us.
1961 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001962 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001963 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001964
Christopher Tate8e294d42011-08-31 20:37:12 -07001965 mSavedStateName = new File(mStateDir, packageName);
1966 mBackupDataName = new File(mDataDir, packageName + ".data");
1967 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001968
Christopher Tate8e294d42011-08-31 20:37:12 -07001969 mSavedState = null;
1970 mBackupData = null;
1971 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001972
Christopher Tate4a627c72011-04-01 14:43:32 -07001973 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001974 try {
1975 // Look up the package info & signatures. This is first so that if it
1976 // throws an exception, there's no file setup yet that would need to
1977 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001978 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001979 // The metadata 'package' is synthetic; construct one and make
1980 // sure our global state is pointed at it
1981 mCurrentPackage = new PackageInfo();
1982 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07001983 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001984
Christopher Tatec7b31e32009-06-10 15:49:30 -07001985 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001986 // the saved-state "file". This is by definition an incremental,
1987 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07001988 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07001989 ParcelFileDescriptor.MODE_READ_ONLY |
1990 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001991
Christopher Tate8e294d42011-08-31 20:37:12 -07001992 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001993 ParcelFileDescriptor.MODE_READ_WRITE |
1994 ParcelFileDescriptor.MODE_CREATE |
1995 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001996
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001998 ParcelFileDescriptor.MODE_READ_WRITE |
1999 ParcelFileDescriptor.MODE_CREATE |
2000 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002001
Christopher Tate44a27902010-01-27 17:15:49 -08002002 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07002003 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2004 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002005 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002006 Slog.e(TAG, "Error invoking for backup on " + packageName);
2007 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2008 e.toString());
2009 agentErrorCleanup();
2010 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002011 }
2012
Christopher Tate8e294d42011-08-31 20:37:12 -07002013 // At this point the agent is off and running. The next thing to happen will
2014 // either be a callback from the agent, at which point we'll process its data
2015 // for transport, or a timeout. Either way the next phase will happen in
2016 // response to the TimeoutHandler interface callbacks.
2017 return BackupConstants.TRANSPORT_OK;
2018 }
2019
2020 @Override
2021 public void operationComplete() {
2022 // Okay, the agent successfully reported back to us. Spin the data off to the
2023 // transport and proceed with the next stage.
2024 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2025 + mCurrentPackage.packageName);
2026 mBackupHandler.removeMessages(MSG_TIMEOUT);
2027 clearAgentState();
2028
2029 ParcelFileDescriptor backupData = null;
2030 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002031 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002032 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002033 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 if (mStatus == BackupConstants.TRANSPORT_OK) {
2035 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002036 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002037 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002038 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002039
Dan Egnor83861e72009-09-17 16:17:55 -07002040 // TODO - We call finishBackup() for each application backed up, because
2041 // we need to know now whether it succeeded or failed. Instead, we should
2042 // hold off on finishBackup() until the end, which implies holding off on
2043 // renaming *all* the output state files (see below) until that happens.
2044
Christopher Tate8e294d42011-08-31 20:37:12 -07002045 if (mStatus == BackupConstants.TRANSPORT_OK) {
2046 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002047 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002048 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002049 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002050 }
2051
2052 // After successful transport, delete the now-stale data
2053 // and juggle the files so that next time we supply the agent
2054 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002055 if (mStatus == BackupConstants.TRANSPORT_OK) {
2056 mBackupDataName.delete();
2057 mNewStateName.renameTo(mSavedStateName);
2058 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2059 mCurrentPackage.packageName, size);
2060 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002061 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002062 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2063 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002064 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002065 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002066 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2067 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2068 mCurrentPackage.packageName);
2069 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002070 } finally {
2071 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002072 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002073
Christopher Tate8e294d42011-08-31 20:37:12 -07002074 // If we encountered an error here it's a transport-level failure. That
2075 // means we need to halt everything and reschedule everything for next time.
2076 final BackupState nextState;
2077 if (mStatus != BackupConstants.TRANSPORT_OK) {
2078 revertAndEndBackup();
2079 nextState = BackupState.FINAL;
2080 } else {
2081 // Success! Proceed with the next app if any, otherwise we're done.
2082 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2083 }
2084
2085 executeNextState(nextState);
2086 }
2087
2088 @Override
2089 public void handleTimeout() {
2090 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2091 // it for the next time we run a backup pass.
2092 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2093 // fail repeatedly (i.e. have proved themselves to be buggy).
2094 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2095 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2096 "timeout");
2097 agentErrorCleanup();
2098 dataChangedImpl(mCurrentPackage.packageName);
2099 }
2100
2101 void revertAndEndBackup() {
2102 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2103 for (BackupRequest request : mOriginalQueue) {
2104 dataChangedImpl(request.packageName);
2105 }
2106 // We also want to reset the backup schedule based on whatever
2107 // the transport suggests by way of retry/backoff time.
2108 restartBackupAlarm();
2109 }
2110
2111 void agentErrorCleanup() {
2112 mBackupDataName.delete();
2113 mNewStateName.delete();
2114 clearAgentState();
2115
2116 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2117 }
2118
2119 // Cleanup common to both success and failure cases
2120 void clearAgentState() {
2121 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2122 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2123 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2124 mSavedState = mBackupData = mNewState = null;
2125 synchronized (mCurrentOpLock) {
2126 mCurrentOperations.clear();
2127 }
2128
2129 // If this was a pseudopackage there's no associated Activity Manager state
2130 if (mCurrentPackage.applicationInfo != null) {
2131 try { // unbind even on timeout, just in case
2132 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2133 } catch (RemoteException e) {}
2134 }
2135 }
2136
2137 void restartBackupAlarm() {
2138 synchronized (mQueueLock) {
2139 try {
2140 startBackupAlarmsLocked(mTransport.requestBackupTime());
2141 } catch (RemoteException e) { /* cannot happen */ }
2142 }
2143 }
2144
2145 void executeNextState(BackupState nextState) {
2146 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2147 + this + " nextState=" + nextState);
2148 mCurrentState = nextState;
2149 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2150 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002151 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002152 }
2153
Christopher Tatedf01dea2009-06-09 20:45:02 -07002154
Christopher Tate4a627c72011-04-01 14:43:32 -07002155 // ----- Full backup to a file/socket -----
2156
2157 class PerformFullBackupTask implements Runnable {
2158 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002159 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002160 IFullBackupRestoreObserver mObserver;
2161 boolean mIncludeApks;
2162 boolean mIncludeShared;
2163 boolean mAllApps;
2164 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002165 String mCurrentPassword;
2166 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002167 AtomicBoolean mLatchObject;
2168 File mFilesDir;
2169 File mManifestFile;
2170
Christopher Tate7926a692011-07-11 11:31:57 -07002171 class FullBackupRunner implements Runnable {
2172 PackageInfo mPackage;
2173 IBackupAgent mAgent;
2174 ParcelFileDescriptor mPipe;
2175 int mToken;
2176 boolean mSendApk;
2177
2178 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2179 int token, boolean sendApk) throws IOException {
2180 mPackage = pack;
2181 mAgent = agent;
2182 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2183 mToken = token;
2184 mSendApk = sendApk;
2185 }
2186
2187 @Override
2188 public void run() {
2189 try {
2190 BackupDataOutput output = new BackupDataOutput(
2191 mPipe.getFileDescriptor());
2192
Christopher Tatec58efa62011-08-01 19:20:14 -07002193 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002194 writeAppManifest(mPackage, mManifestFile, mSendApk);
2195 FullBackup.backupToTar(mPackage.packageName, null, null,
2196 mFilesDir.getAbsolutePath(),
2197 mManifestFile.getAbsolutePath(),
2198 output);
2199
2200 if (mSendApk) {
2201 writeApkToBackup(mPackage, output);
2202 }
2203
Christopher Tatec58efa62011-08-01 19:20:14 -07002204 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002205 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002206 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2207 } catch (IOException e) {
2208 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2209 } catch (RemoteException e) {
2210 Slog.e(TAG, "Remote agent vanished during full backup of "
2211 + mPackage.packageName);
2212 } finally {
2213 try {
2214 mPipe.close();
2215 } catch (IOException e) {}
2216 }
2217 }
2218 }
2219
Christopher Tate4a627c72011-04-01 14:43:32 -07002220 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002221 boolean includeApks, boolean includeShared, String curPassword,
2222 String encryptPassword, boolean doAllApps, String[] packages,
2223 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002224 mOutputFile = fd;
2225 mObserver = observer;
2226 mIncludeApks = includeApks;
2227 mIncludeShared = includeShared;
2228 mAllApps = doAllApps;
2229 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002230 mCurrentPassword = curPassword;
2231 // when backing up, if there is a current backup password, we require that
2232 // the user use a nonempty encryption password as well. if one is supplied
2233 // in the UI we use that, but if the UI was left empty we fall back to the
2234 // current backup password (which was supplied by the user as well).
2235 if (encryptPassword == null || "".equals(encryptPassword)) {
2236 mEncryptPassword = curPassword;
2237 } else {
2238 mEncryptPassword = encryptPassword;
2239 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002240 mLatchObject = latch;
2241
2242 mFilesDir = new File("/data/system");
2243 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2244 }
2245
2246 @Override
2247 public void run() {
2248 final List<PackageInfo> packagesToBackup;
2249
Christopher Tateb0628bf2011-06-02 15:08:13 -07002250 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002251 sendStartBackup();
2252
2253 // doAllApps supersedes the package set if any
2254 if (mAllApps) {
2255 packagesToBackup = mPackageManager.getInstalledPackages(
2256 PackageManager.GET_SIGNATURES);
2257 } else {
2258 packagesToBackup = new ArrayList<PackageInfo>();
2259 for (String pkgName : mPackages) {
2260 try {
2261 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2262 PackageManager.GET_SIGNATURES));
2263 } catch (NameNotFoundException e) {
2264 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2265 }
2266 }
2267 }
2268
Christopher Tatea858cb02011-06-03 12:27:51 -07002269 // Cull any packages that have indicated that backups are not permitted.
2270 for (int i = 0; i < packagesToBackup.size(); ) {
2271 PackageInfo info = packagesToBackup.get(i);
2272 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2273 packagesToBackup.remove(i);
2274 } else {
2275 i++;
2276 }
2277 }
2278
Christopher Tate7926a692011-07-11 11:31:57 -07002279 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002280 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002281
Christopher Tate4a627c72011-04-01 14:43:32 -07002282 PackageInfo pkg = null;
2283 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002284 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002285 boolean compressing = COMPRESS_FULL_BACKUPS;
2286 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002287
Christopher Tateeef4ae42011-08-05 13:15:53 -07002288 // Verify that the given password matches the currently-active
2289 // backup password, if any
2290 if (hasBackupPassword()) {
2291 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2292 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2293 return;
2294 }
2295 }
2296
Christopher Tate7bdb0962011-07-13 19:30:21 -07002297 // Write the global file header. All strings are UTF-8 encoded; lines end
2298 // with a '\n' byte. Actual backup data begins immediately following the
2299 // final '\n'.
2300 //
2301 // line 1: "ANDROID BACKUP"
2302 // line 2: backup file format version, currently "1"
2303 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002304 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2305 //
2306 // When line 4 is not "none", then additional header data follows:
2307 //
2308 // line 5: user password salt [hex]
2309 // line 6: master key checksum salt [hex]
2310 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2311 // line 8: IV of the user key [hex]
2312 // line 9: master key blob [hex]
2313 // IV of the master key, master key itself, master key checksum hash
2314 //
2315 // The master key checksum is the master key plus its checksum salt, run through
2316 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2317 // correct password for decrypting the archive: the master key decrypted from
2318 // the archive using the user-supplied password is also run through PBKDF2 in
2319 // this way, and if the result does not match the checksum as stored in the
2320 // archive, then we know that the user-supplied password does not match the
2321 // archive's.
2322 StringBuilder headerbuf = new StringBuilder(1024);
2323
Christopher Tate7bdb0962011-07-13 19:30:21 -07002324 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002325 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2326 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002327
2328 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002329 // Set up the encryption stage if appropriate, and emit the correct header
2330 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002331 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2332 } else {
2333 headerbuf.append("none\n");
2334 }
2335
Christopher Tate7bdb0962011-07-13 19:30:21 -07002336 byte[] header = headerbuf.toString().getBytes("UTF-8");
2337 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002338
2339 // Set up the compression stage feeding into the encryption stage (if any)
2340 if (compressing) {
2341 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2342 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2343 }
2344
2345 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002346 } catch (Exception e) {
2347 // Should never happen!
2348 Slog.e(TAG, "Unable to emit archive header", e);
2349 return;
2350 }
2351
Christopher Tateb0628bf2011-06-02 15:08:13 -07002352 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002353 int N = packagesToBackup.size();
2354 for (int i = 0; i < N; i++) {
2355 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002356 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002357 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002358
Christopher Tate6853fcf2011-08-10 17:52:21 -07002359 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002360 if (mIncludeShared) {
2361 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002362 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002363
2364 // Done!
2365 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002366 } catch (RemoteException e) {
2367 Slog.e(TAG, "App died during full backup");
2368 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002369 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002370 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002371 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002372 mOutputFile.close();
2373 } catch (IOException e) {
2374 /* nothing we can do about this */
2375 }
2376 synchronized (mCurrentOpLock) {
2377 mCurrentOperations.clear();
2378 }
2379 synchronized (mLatchObject) {
2380 mLatchObject.set(true);
2381 mLatchObject.notifyAll();
2382 }
2383 sendEndBackup();
2384 mWakelock.release();
2385 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2386 }
2387 }
2388
Christopher Tate2efd2db2011-07-19 16:32:49 -07002389 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2390 OutputStream ofstream) throws Exception {
2391 // User key will be used to encrypt the master key.
2392 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002393 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002394 PBKDF2_HASH_ROUNDS);
2395
2396 // the master key is random for each backup
2397 byte[] masterPw = new byte[256 / 8];
2398 mRng.nextBytes(masterPw);
2399 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2400
2401 // primary encryption of the datastream with the random key
2402 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2403 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2404 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2405 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2406
2407 // line 4: name of encryption algorithm
2408 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2409 headerbuf.append('\n');
2410 // line 5: user password salt [hex]
2411 headerbuf.append(byteArrayToHex(newUserSalt));
2412 headerbuf.append('\n');
2413 // line 6: master key checksum salt [hex]
2414 headerbuf.append(byteArrayToHex(checksumSalt));
2415 headerbuf.append('\n');
2416 // line 7: number of PBKDF2 rounds used [decimal]
2417 headerbuf.append(PBKDF2_HASH_ROUNDS);
2418 headerbuf.append('\n');
2419
2420 // line 8: IV of the user key [hex]
2421 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2422 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2423
2424 byte[] IV = mkC.getIV();
2425 headerbuf.append(byteArrayToHex(IV));
2426 headerbuf.append('\n');
2427
2428 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2429 // [byte] IV length = Niv
2430 // [array of Niv bytes] IV itself
2431 // [byte] master key length = Nmk
2432 // [array of Nmk bytes] master key itself
2433 // [byte] MK checksum hash length = Nck
2434 // [array of Nck bytes] master key checksum hash
2435 //
2436 // The checksum is the (master key + checksum salt), run through the
2437 // stated number of PBKDF2 rounds
2438 IV = c.getIV();
2439 byte[] mk = masterKeySpec.getEncoded();
2440 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2441 checksumSalt, PBKDF2_HASH_ROUNDS);
2442
2443 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2444 + checksum.length + 3);
2445 DataOutputStream mkOut = new DataOutputStream(blob);
2446 mkOut.writeByte(IV.length);
2447 mkOut.write(IV);
2448 mkOut.writeByte(mk.length);
2449 mkOut.write(mk);
2450 mkOut.writeByte(checksum.length);
2451 mkOut.write(checksum);
2452 mkOut.flush();
2453 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2454 headerbuf.append(byteArrayToHex(encryptedMk));
2455 headerbuf.append('\n');
2456
2457 return finalOutput;
2458 }
2459
2460 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002461 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002462 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2463
2464 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2465 IApplicationThread.BACKUP_MODE_FULL);
2466 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002467 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002468 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002469 pipes = ParcelFileDescriptor.createPipe();
2470
Christopher Tateb0628bf2011-06-02 15:08:13 -07002471 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002472 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002473 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2474 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2475 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2476
2477 sendOnBackupPackage(pkg.packageName);
2478
Christopher Tate7926a692011-07-11 11:31:57 -07002479 final int token = generateToken();
2480 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2481 token, sendApk);
2482 pipes[1].close(); // the runner has dup'd it
2483 pipes[1] = null;
2484 Thread t = new Thread(runner);
2485 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002486
Christopher Tate7926a692011-07-11 11:31:57 -07002487 // Now pull data from the app and stuff it into the compressor
2488 try {
2489 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2490 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002491
Christopher Tate7926a692011-07-11 11:31:57 -07002492 byte[] buffer = new byte[16 * 1024];
2493 int chunkTotal;
2494 while ((chunkTotal = in.readInt()) > 0) {
2495 while (chunkTotal > 0) {
2496 int toRead = (chunkTotal > buffer.length)
2497 ? buffer.length : chunkTotal;
2498 int nRead = in.read(buffer, 0, toRead);
2499 out.write(buffer, 0, nRead);
2500 chunkTotal -= nRead;
2501 }
2502 }
2503 } catch (IOException e) {
2504 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002505 }
2506
Christopher Tateb0628bf2011-06-02 15:08:13 -07002507 if (!waitUntilOperationComplete(token)) {
2508 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2509 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002510 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002511 }
Christopher Tate7926a692011-07-11 11:31:57 -07002512
Christopher Tateb0628bf2011-06-02 15:08:13 -07002513 } catch (IOException e) {
2514 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002515 } finally {
2516 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002517 // flush after every package
2518 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002519 if (pipes != null) {
2520 if (pipes[0] != null) pipes[0].close();
2521 if (pipes[1] != null) pipes[1].close();
2522 }
Christopher Tate7926a692011-07-11 11:31:57 -07002523 } catch (IOException e) {
2524 Slog.w(TAG, "Error bringing down backup stack");
2525 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002526 }
2527 } else {
2528 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2529 }
2530 tearDown(pkg);
2531 }
2532
Christopher Tate79ec80d2011-06-24 14:58:49 -07002533 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2534 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2535 final String appSourceDir = pkg.applicationInfo.sourceDir;
2536 final String apkDir = new File(appSourceDir).getParent();
2537 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2538 apkDir, appSourceDir, output);
2539
2540 // Save associated .obb content if it exists and we did save the apk
2541 // check for .obb and save those too
2542 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2543 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002544 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002545 File[] obbFiles = obbDir.listFiles();
2546 if (obbFiles != null) {
2547 final String obbDirName = obbDir.getAbsolutePath();
2548 for (File obb : obbFiles) {
2549 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2550 obbDirName, obb.getAbsolutePath(), output);
2551 }
2552 }
2553 }
2554 }
2555
Christopher Tateb0628bf2011-06-02 15:08:13 -07002556 private void backupSharedStorage() throws RemoteException {
2557 PackageInfo pkg = null;
2558 try {
2559 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2560 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2561 IApplicationThread.BACKUP_MODE_FULL);
2562 if (agent != null) {
2563 sendOnBackupPackage("Shared storage");
2564
2565 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002566 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002567 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002568 if (!waitUntilOperationComplete(token)) {
2569 Slog.e(TAG, "Full backup failed on shared storage");
2570 } else {
2571 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2572 }
2573 } else {
2574 Slog.e(TAG, "Could not bind to shared storage backup agent");
2575 }
2576 } catch (NameNotFoundException e) {
2577 Slog.e(TAG, "Shared storage backup package not found");
2578 } finally {
2579 tearDown(pkg);
2580 }
2581 }
2582
Christopher Tate6853fcf2011-08-10 17:52:21 -07002583 private void finalizeBackup(OutputStream out) {
2584 try {
2585 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2586 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2587 out.write(eof);
2588 } catch (IOException e) {
2589 Slog.w(TAG, "Error attempting to finalize backup stream");
2590 }
2591 }
2592
Christopher Tate4a627c72011-04-01 14:43:32 -07002593 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2594 throws IOException {
2595 // Manifest format. All data are strings ending in LF:
2596 // BACKUP_MANIFEST_VERSION, currently 1
2597 //
2598 // Version 1:
2599 // package name
2600 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002601 // platform versionCode
2602 // getInstallerPackageName() for this package (maybe empty)
2603 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002604 // number of signatures == N
2605 // N*: signature byte array in ascii format per Signature.toCharsString()
2606 StringBuilder builder = new StringBuilder(4096);
2607 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2608
2609 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2610 printer.println(pkg.packageName);
2611 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002612 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2613
2614 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2615 printer.println((installerName != null) ? installerName : "");
2616
Christopher Tate4a627c72011-04-01 14:43:32 -07002617 printer.println(withApk ? "1" : "0");
2618 if (pkg.signatures == null) {
2619 printer.println("0");
2620 } else {
2621 printer.println(Integer.toString(pkg.signatures.length));
2622 for (Signature sig : pkg.signatures) {
2623 printer.println(sig.toCharsString());
2624 }
2625 }
2626
2627 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002628 outstream.write(builder.toString().getBytes());
2629 outstream.close();
2630 }
2631
2632 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002633 if (pkg != null) {
2634 final ApplicationInfo app = pkg.applicationInfo;
2635 if (app != null) {
2636 try {
2637 // unbind and tidy up even on timeout or failure, just in case
2638 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002639
Christopher Tateb0628bf2011-06-02 15:08:13 -07002640 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002641 if (app.uid != Process.SYSTEM_UID
2642 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002643 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002644 mActivityManager.killApplicationProcess(app.processName, app.uid);
2645 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002646 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002647 }
2648 } catch (RemoteException e) {
2649 Slog.d(TAG, "Lost app trying to shut down");
2650 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002651 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002652 }
2653 }
2654
2655 // wrappers for observer use
2656 void sendStartBackup() {
2657 if (mObserver != null) {
2658 try {
2659 mObserver.onStartBackup();
2660 } catch (RemoteException e) {
2661 Slog.w(TAG, "full backup observer went away: startBackup");
2662 mObserver = null;
2663 }
2664 }
2665 }
2666
2667 void sendOnBackupPackage(String name) {
2668 if (mObserver != null) {
2669 try {
2670 // TODO: use a more user-friendly name string
2671 mObserver.onBackupPackage(name);
2672 } catch (RemoteException e) {
2673 Slog.w(TAG, "full backup observer went away: backupPackage");
2674 mObserver = null;
2675 }
2676 }
2677 }
2678
2679 void sendEndBackup() {
2680 if (mObserver != null) {
2681 try {
2682 mObserver.onEndBackup();
2683 } catch (RemoteException e) {
2684 Slog.w(TAG, "full backup observer went away: endBackup");
2685 mObserver = null;
2686 }
2687 }
2688 }
2689 }
2690
2691
Christopher Tate75a99702011-05-18 16:28:19 -07002692 // ----- Full restore from a file/socket -----
2693
2694 // Description of a file in the restore datastream
2695 static class FileMetadata {
2696 String packageName; // name of the owning app
2697 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002698 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002699 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2700 String path; // subpath within the semantic domain
2701 long mode; // e.g. 0666 (actually int)
2702 long mtime; // last mod time, UTC time_t (actually int)
2703 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002704
2705 @Override
2706 public String toString() {
2707 StringBuilder sb = new StringBuilder(128);
2708 sb.append("FileMetadata{");
2709 sb.append(packageName); sb.append(',');
2710 sb.append(type); sb.append(',');
2711 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2712 sb.append(size);
2713 sb.append('}');
2714 return sb.toString();
2715 }
Christopher Tate75a99702011-05-18 16:28:19 -07002716 }
2717
2718 enum RestorePolicy {
2719 IGNORE,
2720 ACCEPT,
2721 ACCEPT_IF_APK
2722 }
2723
2724 class PerformFullRestoreTask implements Runnable {
2725 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002726 String mCurrentPassword;
2727 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002728 IFullBackupRestoreObserver mObserver;
2729 AtomicBoolean mLatchObject;
2730 IBackupAgent mAgent;
2731 String mAgentPackage;
2732 ApplicationInfo mTargetApp;
2733 ParcelFileDescriptor[] mPipes = null;
2734
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002735 long mBytes;
2736
Christopher Tate75a99702011-05-18 16:28:19 -07002737 // possible handling states for a given package in the restore dataset
2738 final HashMap<String, RestorePolicy> mPackagePolicies
2739 = new HashMap<String, RestorePolicy>();
2740
2741 // installer package names for each encountered app, derived from the manifests
2742 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2743
2744 // Signatures for a given package found in its manifest file
2745 final HashMap<String, Signature[]> mManifestSignatures
2746 = new HashMap<String, Signature[]>();
2747
2748 // Packages we've already wiped data on when restoring their first file
2749 final HashSet<String> mClearedPackages = new HashSet<String>();
2750
Christopher Tate728a1c42011-07-28 18:03:03 -07002751 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002752 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002753 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002754 mCurrentPassword = curPassword;
2755 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002756 mObserver = observer;
2757 mLatchObject = latch;
2758 mAgent = null;
2759 mAgentPackage = null;
2760 mTargetApp = null;
2761
2762 // Which packages we've already wiped data on. We prepopulate this
2763 // with a whitelist of packages known to be unclearable.
2764 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002765 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002766
Christopher Tate75a99702011-05-18 16:28:19 -07002767 }
2768
2769 class RestoreFileRunnable implements Runnable {
2770 IBackupAgent mAgent;
2771 FileMetadata mInfo;
2772 ParcelFileDescriptor mSocket;
2773 int mToken;
2774
2775 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2776 ParcelFileDescriptor socket, int token) throws IOException {
2777 mAgent = agent;
2778 mInfo = info;
2779 mToken = token;
2780
2781 // This class is used strictly for process-local binder invocations. The
2782 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2783 // do not automatically get a 'dup'ed descriptor that we can can continue
2784 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2785 // before proceeding to do the restore.
2786 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2787 }
2788
2789 @Override
2790 public void run() {
2791 try {
2792 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2793 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2794 mToken, mBackupManagerBinder);
2795 } catch (RemoteException e) {
2796 // never happens; this is used strictly for local binder calls
2797 }
2798 }
2799 }
2800
2801 @Override
2802 public void run() {
2803 Slog.i(TAG, "--- Performing full-dataset restore ---");
2804 sendStartRestore();
2805
Christopher Tateb0628bf2011-06-02 15:08:13 -07002806 // Are we able to restore shared-storage data?
2807 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2808 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2809 }
2810
Christopher Tate2efd2db2011-07-19 16:32:49 -07002811 FileInputStream rawInStream = null;
2812 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002813 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002814 if (hasBackupPassword()) {
2815 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2816 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2817 return;
2818 }
2819 }
2820
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002821 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002822 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002823 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2824 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002825
2826 // First, parse out the unencrypted/uncompressed header
2827 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002828 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002829 final InputStream in;
2830
2831 boolean okay = false;
2832 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2833 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002834 rawDataIn.readFully(streamHeader);
2835 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2836 if (Arrays.equals(magicBytes, streamHeader)) {
2837 // okay, header looks good. now parse out the rest of the fields.
2838 String s = readHeaderLine(rawInStream);
2839 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2840 // okay, it's a version we recognize
2841 s = readHeaderLine(rawInStream);
2842 compressed = (Integer.parseInt(s) != 0);
2843 s = readHeaderLine(rawInStream);
2844 if (s.equals("none")) {
2845 // no more header to parse; we're good to go
2846 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002847 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002848 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2849 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002850 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002851 }
2852 } else Slog.w(TAG, "Archive is encrypted but no password given");
2853 } else Slog.w(TAG, "Wrong header version: " + s);
2854 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002855
2856 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002857 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002858 return;
2859 }
2860
2861 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002862 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002863
2864 boolean didRestore;
2865 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002866 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002867 } while (didRestore);
2868
Christopher Tatec58efa62011-08-01 19:20:14 -07002869 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002870 } catch (IOException e) {
2871 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002872 } finally {
2873 tearDownPipes();
2874 tearDownAgent(mTargetApp);
2875
2876 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002877 if (rawDataIn != null) rawDataIn.close();
2878 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002879 mInputFile.close();
2880 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002881 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002882 /* nothing we can do about this */
2883 }
2884 synchronized (mCurrentOpLock) {
2885 mCurrentOperations.clear();
2886 }
2887 synchronized (mLatchObject) {
2888 mLatchObject.set(true);
2889 mLatchObject.notifyAll();
2890 }
2891 sendEndRestore();
2892 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002893 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002894 }
2895 }
2896
Christopher Tate7bdb0962011-07-13 19:30:21 -07002897 String readHeaderLine(InputStream in) throws IOException {
2898 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002899 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002900 while ((c = in.read()) >= 0) {
2901 if (c == '\n') break; // consume and discard the newlines
2902 buffer.append((char)c);
2903 }
2904 return buffer.toString();
2905 }
2906
Christopher Tate2efd2db2011-07-19 16:32:49 -07002907 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2908 InputStream result = null;
2909 try {
2910 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2911
2912 String userSaltHex = readHeaderLine(rawInStream); // 5
2913 byte[] userSalt = hexToByteArray(userSaltHex);
2914
2915 String ckSaltHex = readHeaderLine(rawInStream); // 6
2916 byte[] ckSalt = hexToByteArray(ckSaltHex);
2917
2918 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2919 String userIvHex = readHeaderLine(rawInStream); // 8
2920
2921 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2922
2923 // decrypt the master key blob
2924 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002925 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002926 rounds);
2927 byte[] IV = hexToByteArray(userIvHex);
2928 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2929 c.init(Cipher.DECRYPT_MODE,
2930 new SecretKeySpec(userKey.getEncoded(), "AES"),
2931 ivSpec);
2932 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2933 byte[] mkBlob = c.doFinal(mkCipher);
2934
2935 // first, the master key IV
2936 int offset = 0;
2937 int len = mkBlob[offset++];
2938 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2939 offset += len;
2940 // then the master key itself
2941 len = mkBlob[offset++];
2942 byte[] mk = Arrays.copyOfRange(mkBlob,
2943 offset, offset + len);
2944 offset += len;
2945 // and finally the master key checksum hash
2946 len = mkBlob[offset++];
2947 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2948 offset, offset + len);
2949
2950 // now validate the decrypted master key against the checksum
2951 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2952 if (Arrays.equals(calculatedCk, mkChecksum)) {
2953 ivSpec = new IvParameterSpec(IV);
2954 c.init(Cipher.DECRYPT_MODE,
2955 new SecretKeySpec(mk, "AES"),
2956 ivSpec);
2957 // Only if all of the above worked properly will 'result' be assigned
2958 result = new CipherInputStream(rawInStream, c);
2959 } else Slog.w(TAG, "Incorrect password");
2960 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2961 } catch (InvalidAlgorithmParameterException e) {
2962 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2963 } catch (BadPaddingException e) {
2964 // This case frequently occurs when the wrong password is used to decrypt
2965 // the master key. Use the identical "incorrect password" log text as is
2966 // used in the checksum failure log in order to avoid providing additional
2967 // information to an attacker.
2968 Slog.w(TAG, "Incorrect password");
2969 } catch (IllegalBlockSizeException e) {
2970 Slog.w(TAG, "Invalid block size in master key");
2971 } catch (NoSuchAlgorithmException e) {
2972 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2973 } catch (NoSuchPaddingException e) {
2974 Slog.e(TAG, "Needed padding mechanism unavailable!");
2975 } catch (InvalidKeyException e) {
2976 Slog.w(TAG, "Illegal password; aborting");
2977 } catch (NumberFormatException e) {
2978 Slog.w(TAG, "Can't parse restore data header");
2979 } catch (IOException e) {
2980 Slog.w(TAG, "Can't read input header");
2981 }
2982
2983 return result;
2984 }
2985
Christopher Tate75a99702011-05-18 16:28:19 -07002986 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2987 FileMetadata info;
2988 try {
2989 info = readTarHeaders(instream);
2990 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002991 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002992 dumpFileMetadata(info);
2993 }
2994
2995 final String pkg = info.packageName;
2996 if (!pkg.equals(mAgentPackage)) {
2997 // okay, change in package; set up our various
2998 // bookkeeping if we haven't seen it yet
2999 if (!mPackagePolicies.containsKey(pkg)) {
3000 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3001 }
3002
3003 // Clean up the previous agent relationship if necessary,
3004 // and let the observer know we're considering a new app.
3005 if (mAgent != null) {
3006 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3007 tearDownPipes();
3008 tearDownAgent(mTargetApp);
3009 mTargetApp = null;
3010 mAgentPackage = null;
3011 }
3012 }
3013
3014 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3015 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3016 mPackageInstallers.put(pkg, info.installerPackageName);
3017 // We've read only the manifest content itself at this point,
3018 // so consume the footer before looping around to the next
3019 // input file
3020 skipTarPadding(info.size, instream);
3021 sendOnRestorePackage(pkg);
3022 } else {
3023 // Non-manifest, so it's actual file data. Is this a package
3024 // we're ignoring?
3025 boolean okay = true;
3026 RestorePolicy policy = mPackagePolicies.get(pkg);
3027 switch (policy) {
3028 case IGNORE:
3029 okay = false;
3030 break;
3031
3032 case ACCEPT_IF_APK:
3033 // If we're in accept-if-apk state, then the first file we
3034 // see MUST be the apk.
3035 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3036 if (DEBUG) Slog.d(TAG, "APK file; installing");
3037 // Try to install the app.
3038 String installerName = mPackageInstallers.get(pkg);
3039 okay = installApk(info, installerName, instream);
3040 // good to go; promote to ACCEPT
3041 mPackagePolicies.put(pkg, (okay)
3042 ? RestorePolicy.ACCEPT
3043 : RestorePolicy.IGNORE);
3044 // At this point we've consumed this file entry
3045 // ourselves, so just strip the tar footer and
3046 // go on to the next file in the input stream
3047 skipTarPadding(info.size, instream);
3048 return true;
3049 } else {
3050 // File data before (or without) the apk. We can't
3051 // handle it coherently in this case so ignore it.
3052 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3053 okay = false;
3054 }
3055 break;
3056
3057 case ACCEPT:
3058 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3059 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3060 // we can take the data without the apk, so we
3061 // *want* to do so. skip the apk by declaring this
3062 // one file not-okay without changing the restore
3063 // policy for the package.
3064 okay = false;
3065 }
3066 break;
3067
3068 default:
3069 // Something has gone dreadfully wrong when determining
3070 // the restore policy from the manifest. Ignore the
3071 // rest of this package's data.
3072 Slog.e(TAG, "Invalid policy from manifest");
3073 okay = false;
3074 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3075 break;
3076 }
3077
3078 // If the policy is satisfied, go ahead and set up to pipe the
3079 // data to the agent.
3080 if (DEBUG && okay && mAgent != null) {
3081 Slog.i(TAG, "Reusing existing agent instance");
3082 }
3083 if (okay && mAgent == null) {
3084 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3085
3086 try {
3087 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3088
3089 // If we haven't sent any data to this app yet, we probably
3090 // need to clear it first. Check that.
3091 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003092 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003093 // responsible for coherently managing a full
3094 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003095 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003096 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3097 clearApplicationDataSynchronous(pkg);
3098 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003099 if (DEBUG) Slog.d(TAG, "backup agent ("
3100 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003101 }
3102 mClearedPackages.add(pkg);
3103 } else {
3104 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3105 }
3106
3107 // All set; now set up the IPC and launch the agent
3108 setUpPipes();
3109 mAgent = bindToAgentSynchronous(mTargetApp,
3110 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3111 mAgentPackage = pkg;
3112 } catch (IOException e) {
3113 // fall through to error handling
3114 } catch (NameNotFoundException e) {
3115 // fall through to error handling
3116 }
3117
3118 if (mAgent == null) {
3119 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3120 okay = false;
3121 tearDownPipes();
3122 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3123 }
3124 }
3125
3126 // Sanity check: make sure we never give data to the wrong app. This
3127 // should never happen but a little paranoia here won't go amiss.
3128 if (okay && !pkg.equals(mAgentPackage)) {
3129 Slog.e(TAG, "Restoring data for " + pkg
3130 + " but agent is for " + mAgentPackage);
3131 okay = false;
3132 }
3133
3134 // At this point we have an agent ready to handle the full
3135 // restore data as well as a pipe for sending data to
3136 // that agent. Tell the agent to start reading from the
3137 // pipe.
3138 if (okay) {
3139 boolean agentSuccess = true;
3140 long toCopy = info.size;
3141 final int token = generateToken();
3142 try {
3143 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3144 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003145 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003146 // fire up the app's agent listening on the socket. If
3147 // the agent is running in the system process we can't
3148 // just invoke it asynchronously, so we provide a thread
3149 // for it here.
3150 if (mTargetApp.processName.equals("system")) {
3151 Slog.d(TAG, "system process agent - spinning a thread");
3152 RestoreFileRunnable runner = new RestoreFileRunnable(
3153 mAgent, info, mPipes[0], token);
3154 new Thread(runner).start();
3155 } else {
3156 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3157 info.domain, info.path, info.mode, info.mtime,
3158 token, mBackupManagerBinder);
3159 }
3160 } catch (IOException e) {
3161 // couldn't dup the socket for a process-local restore
3162 Slog.d(TAG, "Couldn't establish restore");
3163 agentSuccess = false;
3164 okay = false;
3165 } catch (RemoteException e) {
3166 // whoops, remote agent went away. We'll eat the content
3167 // ourselves, then, and not copy it over.
3168 Slog.e(TAG, "Agent crashed during full restore");
3169 agentSuccess = false;
3170 okay = false;
3171 }
3172
3173 // Copy over the data if the agent is still good
3174 if (okay) {
3175 boolean pipeOkay = true;
3176 FileOutputStream pipe = new FileOutputStream(
3177 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003178 while (toCopy > 0) {
3179 int toRead = (toCopy > buffer.length)
3180 ? buffer.length : (int)toCopy;
3181 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003182 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003183 if (nRead <= 0) break;
3184 toCopy -= nRead;
3185
3186 // send it to the output pipe as long as things
3187 // are still good
3188 if (pipeOkay) {
3189 try {
3190 pipe.write(buffer, 0, nRead);
3191 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003192 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003193 pipeOkay = false;
3194 }
3195 }
3196 }
3197
3198 // done sending that file! Now we just need to consume
3199 // the delta from info.size to the end of block.
3200 skipTarPadding(info.size, instream);
3201
3202 // and now that we've sent it all, wait for the remote
3203 // side to acknowledge receipt
3204 agentSuccess = waitUntilOperationComplete(token);
3205 }
3206
3207 // okay, if the remote end failed at any point, deal with
3208 // it by ignoring the rest of the restore on it
3209 if (!agentSuccess) {
3210 mBackupHandler.removeMessages(MSG_TIMEOUT);
3211 tearDownPipes();
3212 tearDownAgent(mTargetApp);
3213 mAgent = null;
3214 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3215 }
3216 }
3217
3218 // Problems setting up the agent communication, or an already-
3219 // ignored package: skip to the next tar stream entry by
3220 // reading and discarding this file.
3221 if (!okay) {
3222 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3223 long bytesToConsume = (info.size + 511) & ~511;
3224 while (bytesToConsume > 0) {
3225 int toRead = (bytesToConsume > buffer.length)
3226 ? buffer.length : (int)bytesToConsume;
3227 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003228 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003229 if (nRead <= 0) break;
3230 bytesToConsume -= nRead;
3231 }
3232 }
3233 }
3234 }
3235 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003236 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003237 // treat as EOF
3238 info = null;
3239 }
3240
3241 return (info != null);
3242 }
3243
3244 void setUpPipes() throws IOException {
3245 mPipes = ParcelFileDescriptor.createPipe();
3246 }
3247
3248 void tearDownPipes() {
3249 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003250 try {
3251 mPipes[0].close();
3252 mPipes[0] = null;
3253 mPipes[1].close();
3254 mPipes[1] = null;
3255 } catch (IOException e) {
3256 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003257 }
3258 mPipes = null;
3259 }
3260 }
3261
3262 void tearDownAgent(ApplicationInfo app) {
3263 if (mAgent != null) {
3264 try {
3265 // unbind and tidy up even on timeout or failure, just in case
3266 mActivityManager.unbindBackupAgent(app);
3267
3268 // The agent was running with a stub Application object, so shut it down.
3269 // !!! We hardcode the confirmation UI's package name here rather than use a
3270 // manifest flag! TODO something less direct.
3271 if (app.uid != Process.SYSTEM_UID
3272 && !app.packageName.equals("com.android.backupconfirm")) {
3273 if (DEBUG) Slog.d(TAG, "Killing host process");
3274 mActivityManager.killApplicationProcess(app.processName, app.uid);
3275 } else {
3276 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3277 }
3278 } catch (RemoteException e) {
3279 Slog.d(TAG, "Lost app trying to shut down");
3280 }
3281 mAgent = null;
3282 }
3283 }
3284
3285 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3286 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003287 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003288 int mResult;
3289
3290 public void reset() {
3291 synchronized (mDone) {
3292 mDone.set(false);
3293 }
3294 }
3295
3296 public void waitForCompletion() {
3297 synchronized (mDone) {
3298 while (mDone.get() == false) {
3299 try {
3300 mDone.wait();
3301 } catch (InterruptedException e) { }
3302 }
3303 }
3304 }
3305
3306 int getResult() {
3307 return mResult;
3308 }
3309
3310 @Override
3311 public void packageInstalled(String packageName, int returnCode)
3312 throws RemoteException {
3313 synchronized (mDone) {
3314 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003315 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003316 mDone.set(true);
3317 mDone.notifyAll();
3318 }
3319 }
3320 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003321
3322 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3323 final AtomicBoolean mDone = new AtomicBoolean();
3324 int mResult;
3325
3326 public void reset() {
3327 synchronized (mDone) {
3328 mDone.set(false);
3329 }
3330 }
3331
3332 public void waitForCompletion() {
3333 synchronized (mDone) {
3334 while (mDone.get() == false) {
3335 try {
3336 mDone.wait();
3337 } catch (InterruptedException e) { }
3338 }
3339 }
3340 }
3341
3342 @Override
3343 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3344 synchronized (mDone) {
3345 mResult = returnCode;
3346 mDone.set(true);
3347 mDone.notifyAll();
3348 }
3349 }
3350 }
3351
Christopher Tate75a99702011-05-18 16:28:19 -07003352 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003353 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003354
3355 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3356 boolean okay = true;
3357
3358 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3359
3360 // The file content is an .apk file. Copy it out to a staging location and
3361 // attempt to install it.
3362 File apkFile = new File(mDataDir, info.packageName);
3363 try {
3364 FileOutputStream apkStream = new FileOutputStream(apkFile);
3365 byte[] buffer = new byte[32 * 1024];
3366 long size = info.size;
3367 while (size > 0) {
3368 long toRead = (buffer.length < size) ? buffer.length : size;
3369 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003370 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003371 apkStream.write(buffer, 0, didRead);
3372 size -= didRead;
3373 }
3374 apkStream.close();
3375
3376 // make sure the installer can read it
3377 apkFile.setReadable(true, false);
3378
3379 // Now install it
3380 Uri packageUri = Uri.fromFile(apkFile);
3381 mInstallObserver.reset();
3382 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003383 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3384 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003385 mInstallObserver.waitForCompletion();
3386
3387 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3388 // The only time we continue to accept install of data even if the
3389 // apk install failed is if we had already determined that we could
3390 // accept the data regardless.
3391 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3392 okay = false;
3393 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003394 } else {
3395 // Okay, the install succeeded. Make sure it was the right app.
3396 boolean uninstall = false;
3397 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3398 Slog.w(TAG, "Restore stream claimed to include apk for "
3399 + info.packageName + " but apk was really "
3400 + mInstallObserver.mPackageName);
3401 // delete the package we just put in place; it might be fraudulent
3402 okay = false;
3403 uninstall = true;
3404 } else {
3405 try {
3406 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3407 PackageManager.GET_SIGNATURES);
3408 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3409 Slog.w(TAG, "Restore stream contains apk of package "
3410 + info.packageName + " but it disallows backup/restore");
3411 okay = false;
3412 } else {
3413 // So far so good -- do the signatures match the manifest?
3414 Signature[] sigs = mManifestSignatures.get(info.packageName);
3415 if (!signaturesMatch(sigs, pkg)) {
3416 Slog.w(TAG, "Installed app " + info.packageName
3417 + " signatures do not match restore manifest");
3418 okay = false;
3419 uninstall = true;
3420 }
3421 }
3422 } catch (NameNotFoundException e) {
3423 Slog.w(TAG, "Install of package " + info.packageName
3424 + " succeeded but now not found");
3425 okay = false;
3426 }
3427 }
3428
3429 // If we're not okay at this point, we need to delete the package
3430 // that we just installed.
3431 if (uninstall) {
3432 mDeleteObserver.reset();
3433 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3434 mDeleteObserver, 0);
3435 mDeleteObserver.waitForCompletion();
3436 }
Christopher Tate75a99702011-05-18 16:28:19 -07003437 }
3438 } catch (IOException e) {
3439 Slog.e(TAG, "Unable to transcribe restored apk for install");
3440 okay = false;
3441 } finally {
3442 apkFile.delete();
3443 }
3444
3445 return okay;
3446 }
3447
3448 // Given an actual file content size, consume the post-content padding mandated
3449 // by the tar format.
3450 void skipTarPadding(long size, InputStream instream) throws IOException {
3451 long partial = (size + 512) % 512;
3452 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003453 final int needed = 512 - (int)partial;
3454 byte[] buffer = new byte[needed];
3455 if (readExactly(instream, buffer, 0, needed) == needed) {
3456 mBytes += needed;
3457 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003458 }
3459 }
3460
3461 // Returns a policy constant; takes a buffer arg to reduce memory churn
3462 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3463 throws IOException {
3464 // Fail on suspiciously large manifest files
3465 if (info.size > 64 * 1024) {
3466 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3467 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003468
Christopher Tate75a99702011-05-18 16:28:19 -07003469 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003470 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3471 mBytes += info.size;
3472 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003473
3474 RestorePolicy policy = RestorePolicy.IGNORE;
3475 String[] str = new String[1];
3476 int offset = 0;
3477
3478 try {
3479 offset = extractLine(buffer, offset, str);
3480 int version = Integer.parseInt(str[0]);
3481 if (version == BACKUP_MANIFEST_VERSION) {
3482 offset = extractLine(buffer, offset, str);
3483 String manifestPackage = str[0];
3484 // TODO: handle <original-package>
3485 if (manifestPackage.equals(info.packageName)) {
3486 offset = extractLine(buffer, offset, str);
3487 version = Integer.parseInt(str[0]); // app version
3488 offset = extractLine(buffer, offset, str);
3489 int platformVersion = Integer.parseInt(str[0]);
3490 offset = extractLine(buffer, offset, str);
3491 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3492 offset = extractLine(buffer, offset, str);
3493 boolean hasApk = str[0].equals("1");
3494 offset = extractLine(buffer, offset, str);
3495 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003496 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003497 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003498 for (int i = 0; i < numSigs; i++) {
3499 offset = extractLine(buffer, offset, str);
3500 sigs[i] = new Signature(str[0]);
3501 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003502 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003503
3504 // Okay, got the manifest info we need...
3505 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003506 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3507 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003508 // Fall through to IGNORE if the app explicitly disallows backup
3509 final int flags = pkgInfo.applicationInfo.flags;
3510 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3511 // Verify signatures against any installed version; if they
3512 // don't match, then we fall though and ignore the data. The
3513 // signatureMatch() method explicitly ignores the signature
3514 // check for packages installed on the system partition, because
3515 // such packages are signed with the platform cert instead of
3516 // the app developer's cert, so they're different on every
3517 // device.
3518 if (signaturesMatch(sigs, pkgInfo)) {
3519 if (pkgInfo.versionCode >= version) {
3520 Slog.i(TAG, "Sig + version match; taking data");
3521 policy = RestorePolicy.ACCEPT;
3522 } else {
3523 // The data is from a newer version of the app than
3524 // is presently installed. That means we can only
3525 // use it if the matching apk is also supplied.
3526 Slog.d(TAG, "Data version " + version
3527 + " is newer than installed version "
3528 + pkgInfo.versionCode + " - requiring apk");
3529 policy = RestorePolicy.ACCEPT_IF_APK;
3530 }
Christopher Tate75a99702011-05-18 16:28:19 -07003531 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003532 Slog.w(TAG, "Restore manifest signatures do not match "
3533 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003534 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003535 } else {
3536 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3537 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003538 }
3539 } catch (NameNotFoundException e) {
3540 // Okay, the target app isn't installed. We can process
3541 // the restore properly only if the dataset provides the
3542 // apk file and we can successfully install it.
3543 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3544 + " not installed; requiring apk in dataset");
3545 policy = RestorePolicy.ACCEPT_IF_APK;
3546 }
3547
3548 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3549 Slog.i(TAG, "Cannot restore package " + info.packageName
3550 + " without the matching .apk");
3551 }
3552 } else {
3553 Slog.i(TAG, "Missing signature on backed-up package "
3554 + info.packageName);
3555 }
3556 } else {
3557 Slog.i(TAG, "Expected package " + info.packageName
3558 + " but restore manifest claims " + manifestPackage);
3559 }
3560 } else {
3561 Slog.i(TAG, "Unknown restore manifest version " + version
3562 + " for package " + info.packageName);
3563 }
3564 } catch (NumberFormatException e) {
3565 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003566 } catch (IllegalArgumentException e) {
3567 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003568 }
3569
3570 return policy;
3571 }
3572
3573 // Builds a line from a byte buffer starting at 'offset', and returns
3574 // the index of the next unconsumed data in the buffer.
3575 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3576 final int end = buffer.length;
3577 if (offset >= end) throw new IOException("Incomplete data");
3578
3579 int pos;
3580 for (pos = offset; pos < end; pos++) {
3581 byte c = buffer[pos];
3582 // at LF we declare end of line, and return the next char as the
3583 // starting point for the next time through
3584 if (c == '\n') {
3585 break;
3586 }
3587 }
3588 outStr[0] = new String(buffer, offset, pos - offset);
3589 pos++; // may be pointing an extra byte past the end but that's okay
3590 return pos;
3591 }
3592
3593 void dumpFileMetadata(FileMetadata info) {
3594 if (DEBUG) {
3595 StringBuilder b = new StringBuilder(128);
3596
3597 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003598 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003599 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3600 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3601 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3602 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3603 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3604 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3605 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3606 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3607 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3608 b.append(String.format(" %9d ", info.size));
3609
3610 Date stamp = new Date(info.mtime);
3611 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3612
3613 b.append(info.packageName);
3614 b.append(" :: ");
3615 b.append(info.domain);
3616 b.append(" :: ");
3617 b.append(info.path);
3618
3619 Slog.i(TAG, b.toString());
3620 }
3621 }
3622 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3623 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3624 byte[] block = new byte[512];
3625 FileMetadata info = null;
3626
3627 boolean gotHeader = readTarHeader(instream, block);
3628 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003629 try {
3630 // okay, presume we're okay, and extract the various metadata
3631 info = new FileMetadata();
3632 info.size = extractRadix(block, 124, 12, 8);
3633 info.mtime = extractRadix(block, 136, 12, 8);
3634 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003635
Christopher Tate2efd2db2011-07-19 16:32:49 -07003636 info.path = extractString(block, 345, 155); // prefix
3637 String path = extractString(block, 0, 100);
3638 if (path.length() > 0) {
3639 if (info.path.length() > 0) info.path += '/';
3640 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003641 }
Christopher Tate75a99702011-05-18 16:28:19 -07003642
Christopher Tate2efd2db2011-07-19 16:32:49 -07003643 // tar link indicator field: 1 byte at offset 156 in the header.
3644 int typeChar = block[156];
3645 if (typeChar == 'x') {
3646 // pax extended header, so we need to read that
3647 gotHeader = readPaxExtendedHeader(instream, info);
3648 if (gotHeader) {
3649 // and after a pax extended header comes another real header -- read
3650 // that to find the real file type
3651 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003652 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003653 if (!gotHeader) throw new IOException("Bad or missing pax header");
3654
3655 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003656 }
Christopher Tate75a99702011-05-18 16:28:19 -07003657
Christopher Tate2efd2db2011-07-19 16:32:49 -07003658 switch (typeChar) {
3659 case '0': info.type = BackupAgent.TYPE_FILE; break;
3660 case '5': {
3661 info.type = BackupAgent.TYPE_DIRECTORY;
3662 if (info.size != 0) {
3663 Slog.w(TAG, "Directory entry with nonzero size in header");
3664 info.size = 0;
3665 }
3666 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003667 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003668 case 0: {
3669 // presume EOF
3670 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3671 return null;
3672 }
3673 default: {
3674 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3675 throw new IOException("Unknown entity type " + typeChar);
3676 }
Christopher Tate75a99702011-05-18 16:28:19 -07003677 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003678
3679 // Parse out the path
3680 //
3681 // first: apps/shared/unrecognized
3682 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3683 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3684 // File in shared storage. !!! TODO: implement this.
3685 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3686 info.packageName = "com.android.sharedstoragebackup";
3687 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3688 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3689 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3690 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3691 // App content! Parse out the package name and domain
3692
3693 // strip the apps/ prefix
3694 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3695
3696 // extract the package name
3697 int slash = info.path.indexOf('/');
3698 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3699 info.packageName = info.path.substring(0, slash);
3700 info.path = info.path.substring(slash+1);
3701
3702 // if it's a manifest we're done, otherwise parse out the domains
3703 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3704 slash = info.path.indexOf('/');
3705 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3706 info.domain = info.path.substring(0, slash);
3707 // validate that it's one of the domains we understand
3708 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3709 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3710 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3711 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3712 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3713 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3714 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3715 throw new IOException("Unrecognized domain " + info.domain);
3716 }
3717
3718 info.path = info.path.substring(slash + 1);
3719 }
3720 }
3721 } catch (IOException e) {
3722 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003723 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003724 HEXLOG(block);
3725 }
3726 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003727 }
3728 }
3729 return info;
3730 }
3731
Christopher Tate2efd2db2011-07-19 16:32:49 -07003732 private void HEXLOG(byte[] block) {
3733 int offset = 0;
3734 int todo = block.length;
3735 StringBuilder buf = new StringBuilder(64);
3736 while (todo > 0) {
3737 buf.append(String.format("%04x ", offset));
3738 int numThisLine = (todo > 16) ? 16 : todo;
3739 for (int i = 0; i < numThisLine; i++) {
3740 buf.append(String.format("%02x ", block[offset+i]));
3741 }
3742 Slog.i("hexdump", buf.toString());
3743 buf.setLength(0);
3744 todo -= numThisLine;
3745 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003746 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003747 }
3748
Christopher Tate6853fcf2011-08-10 17:52:21 -07003749 // Read exactly the given number of bytes into a buffer at the stated offset.
3750 // Returns false if EOF is encountered before the requested number of bytes
3751 // could be read.
3752 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3753 throws IOException {
3754 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3755
3756 int soFar = 0;
3757 while (soFar < size) {
3758 int nRead = in.read(buffer, offset + soFar, size - soFar);
3759 if (nRead <= 0) {
3760 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3761 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003762 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003763 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003764 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003765 return soFar;
3766 }
3767
3768 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3769 final int got = readExactly(instream, block, 0, 512);
3770 if (got == 0) return false; // Clean EOF
3771 if (got < 512) throw new IOException("Unable to read full block header");
3772 mBytes += 512;
3773 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003774 }
3775
3776 // overwrites 'info' fields based on the pax extended header
3777 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3778 throws IOException {
3779 // We should never see a pax extended header larger than this
3780 if (info.size > 32*1024) {
3781 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3782 + " - aborting");
3783 throw new IOException("Sanity failure: pax header size " + info.size);
3784 }
3785
3786 // read whole blocks, not just the content size
3787 int numBlocks = (int)((info.size + 511) >> 9);
3788 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003789 if (readExactly(instream, data, 0, data.length) < data.length) {
3790 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003791 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003792 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003793
3794 final int contentSize = (int) info.size;
3795 int offset = 0;
3796 do {
3797 // extract the line at 'offset'
3798 int eol = offset+1;
3799 while (eol < contentSize && data[eol] != ' ') eol++;
3800 if (eol >= contentSize) {
3801 // error: we just hit EOD looking for the end of the size field
3802 throw new IOException("Invalid pax data");
3803 }
3804 // eol points to the space between the count and the key
3805 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3806 int key = eol + 1; // start of key=value
3807 eol = offset + linelen - 1; // trailing LF
3808 int value;
3809 for (value = key+1; data[value] != '=' && value <= eol; value++);
3810 if (value > eol) {
3811 throw new IOException("Invalid pax declaration");
3812 }
3813
3814 // pax requires that key/value strings be in UTF-8
3815 String keyStr = new String(data, key, value-key, "UTF-8");
3816 // -1 to strip the trailing LF
3817 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3818
3819 if ("path".equals(keyStr)) {
3820 info.path = valStr;
3821 } else if ("size".equals(keyStr)) {
3822 info.size = Long.parseLong(valStr);
3823 } else {
3824 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3825 }
3826
3827 offset += linelen;
3828 } while (offset < contentSize);
3829
3830 return true;
3831 }
3832
3833 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3834 throws IOException {
3835 long value = 0;
3836 final int end = offset + maxChars;
3837 for (int i = offset; i < end; i++) {
3838 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003839 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003840 if (b == 0 || b == ' ') break;
3841 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003842 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003843 }
3844 value = radix * value + (b - '0');
3845 }
3846 return value;
3847 }
3848
3849 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3850 final int end = offset + maxChars;
3851 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003852 // tar string fields terminate early with a NUL
3853 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003854 return new String(data, offset, eos-offset, "US-ASCII");
3855 }
3856
3857 void sendStartRestore() {
3858 if (mObserver != null) {
3859 try {
3860 mObserver.onStartRestore();
3861 } catch (RemoteException e) {
3862 Slog.w(TAG, "full restore observer went away: startRestore");
3863 mObserver = null;
3864 }
3865 }
3866 }
3867
3868 void sendOnRestorePackage(String name) {
3869 if (mObserver != null) {
3870 try {
3871 // TODO: use a more user-friendly name string
3872 mObserver.onRestorePackage(name);
3873 } catch (RemoteException e) {
3874 Slog.w(TAG, "full restore observer went away: restorePackage");
3875 mObserver = null;
3876 }
3877 }
3878 }
3879
3880 void sendEndRestore() {
3881 if (mObserver != null) {
3882 try {
3883 mObserver.onEndRestore();
3884 } catch (RemoteException e) {
3885 Slog.w(TAG, "full restore observer went away: endRestore");
3886 mObserver = null;
3887 }
3888 }
3889 }
3890 }
3891
Christopher Tatedf01dea2009-06-09 20:45:02 -07003892 // ----- Restore handling -----
3893
Christopher Tate78dd4a72009-11-04 11:49:08 -08003894 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3895 // If the target resides on the system partition, we allow it to restore
3896 // data from the like-named package in a restore set even if the signatures
3897 // do not match. (Unlike general applications, those flashed to the system
3898 // partition will be signed with the device's platform certificate, so on
3899 // different phones the same system app will have different signatures.)
3900 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003901 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003902 return true;
3903 }
3904
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003905 // Allow unsigned apps, but not signed on one device and unsigned on the other
3906 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003907 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003908 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003909 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003910 if ((storedSigs == null || storedSigs.length == 0)
3911 && (deviceSigs == null || deviceSigs.length == 0)) {
3912 return true;
3913 }
3914 if (storedSigs == null || deviceSigs == null) {
3915 return false;
3916 }
3917
Christopher Tateabce4e82009-06-18 18:35:32 -07003918 // !!! TODO: this demands that every stored signature match one
3919 // that is present on device, and does not demand the converse.
3920 // Is this this right policy?
3921 int nStored = storedSigs.length;
3922 int nDevice = deviceSigs.length;
3923
3924 for (int i=0; i < nStored; i++) {
3925 boolean match = false;
3926 for (int j=0; j < nDevice; j++) {
3927 if (storedSigs[i].equals(deviceSigs[j])) {
3928 match = true;
3929 break;
3930 }
3931 }
3932 if (!match) {
3933 return false;
3934 }
3935 }
3936 return true;
3937 }
3938
Christopher Tate2982d062011-09-06 20:35:24 -07003939 enum RestoreState {
3940 INITIAL,
3941 DOWNLOAD_DATA,
3942 PM_METADATA,
3943 RUNNING_QUEUE,
3944 FINAL
3945 }
3946
3947 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003948 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003949 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003950 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003951 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003952 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003953 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003954 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003955 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07003956 private long mStartRealtime;
3957 private PackageManagerBackupAgent mPmAgent;
3958 private List<PackageInfo> mAgentPackages;
3959 private ArrayList<PackageInfo> mRestorePackages;
3960 private RestoreState mCurrentState;
3961 private int mCount;
3962 private boolean mFinished;
3963 private int mStatus;
3964 private File mBackupDataName;
3965 private File mNewStateName;
3966 private File mSavedStateName;
3967 private ParcelFileDescriptor mBackupData;
3968 private ParcelFileDescriptor mNewState;
3969 private PackageInfo mCurrentPackage;
3970
Christopher Tatedf01dea2009-06-09 20:45:02 -07003971
Christopher Tate5cbbf562009-06-22 16:44:51 -07003972 class RestoreRequest {
3973 public PackageInfo app;
3974 public int storedAppVersion;
3975
3976 RestoreRequest(PackageInfo _app, int _version) {
3977 app = _app;
3978 storedAppVersion = _version;
3979 }
3980 }
3981
Christopher Tate44a27902010-01-27 17:15:49 -08003982 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003983 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003984 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07003985 mCurrentState = RestoreState.INITIAL;
3986 mFinished = false;
3987 mPmAgent = null;
3988
Christopher Tatedf01dea2009-06-09 20:45:02 -07003989 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003990 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003991 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003992 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003993 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003994 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003995
Christopher Tate284f1bb2011-07-07 14:31:18 -07003996 if (filterSet != null) {
3997 mFilterSet = new HashSet<String>();
3998 for (String pkg : filterSet) {
3999 mFilterSet.add(pkg);
4000 }
4001 } else {
4002 mFilterSet = null;
4003 }
4004
Christopher Tate5cb400b2009-06-25 16:03:14 -07004005 try {
4006 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4007 } catch (RemoteException e) {
4008 // can't happen; the transport is local
4009 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004010 }
4011
Christopher Tate2982d062011-09-06 20:35:24 -07004012 // Execute one tick of whatever state machine the task implements
4013 @Override
4014 public void execute() {
4015 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4016 switch (mCurrentState) {
4017 case INITIAL:
4018 beginRestore();
4019 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004020
Christopher Tate2982d062011-09-06 20:35:24 -07004021 case DOWNLOAD_DATA:
4022 downloadRestoreData();
4023 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004024
Christopher Tate2982d062011-09-06 20:35:24 -07004025 case PM_METADATA:
4026 restorePmMetadata();
4027 break;
4028
4029 case RUNNING_QUEUE:
4030 restoreNextAgent();
4031 break;
4032
4033 case FINAL:
4034 if (!mFinished) finalizeRestore();
4035 else {
4036 Slog.e(TAG, "Duplicate finish");
4037 }
4038 mFinished = true;
4039 break;
4040 }
4041 }
4042
4043 // Initialize and set up for the PM metadata restore, which comes first
4044 void beginRestore() {
4045 // Don't account time doing the restore as inactivity of the app
4046 // that has opened a restore session.
4047 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4048
4049 // Assume error until we successfully init everything
4050 mStatus = BackupConstants.TRANSPORT_ERROR;
4051
Christopher Tatedf01dea2009-06-09 20:45:02 -07004052 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004053 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004054 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004055
Dan Egnorefe52642009-06-24 00:16:33 -07004056 // Get the list of all packages which have backup enabled.
4057 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004058 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004059 PackageInfo omPackage = new PackageInfo();
4060 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004061 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004062
Christopher Tate2982d062011-09-06 20:35:24 -07004063 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004064 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004065 // if there's a filter set, strip out anything that isn't
4066 // present before proceeding
4067 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004068 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4069 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004070 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004071 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004072 }
4073 }
Christopher Tate2982d062011-09-06 20:35:24 -07004074 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004075 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004076 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004077 Slog.i(TAG, " " + p);
4078 }
4079 }
4080 }
Christopher Tate2982d062011-09-06 20:35:24 -07004081 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004082 } else {
4083 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004084 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004085 }
Dan Egnorefe52642009-06-24 00:16:33 -07004086
Christopher Tate7d562ec2009-06-25 18:03:43 -07004087 // let the observer know that we're running
4088 if (mObserver != null) {
4089 try {
4090 // !!! TODO: get an actual count from the transport after
4091 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004092 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004093 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004095 mObserver = null;
4096 }
4097 }
Christopher Tate2982d062011-09-06 20:35:24 -07004098 } catch (RemoteException e) {
4099 // Something has gone catastrophically wrong with the transport
4100 Slog.e(TAG, "Error communicating with transport for restore");
4101 executeNextState(RestoreState.FINAL);
4102 return;
4103 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004104
Christopher Tate2982d062011-09-06 20:35:24 -07004105 mStatus = BackupConstants.TRANSPORT_OK;
4106 executeNextState(RestoreState.DOWNLOAD_DATA);
4107 }
4108
4109 void downloadRestoreData() {
4110 // Note that the download phase can be very time consuming, but we're executing
4111 // it inline here on the looper. This is "okay" because it is not calling out to
4112 // third party code; the transport is "trusted," and so we assume it is being a
4113 // good citizen and timing out etc when appropriate.
4114 //
4115 // TODO: when appropriate, move the download off the looper and rearrange the
4116 // error handling around that.
4117 try {
4118 mStatus = mTransport.startRestore(mToken,
4119 mRestorePackages.toArray(new PackageInfo[0]));
4120 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004121 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004122 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004123 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004124 return;
4125 }
Christopher Tate2982d062011-09-06 20:35:24 -07004126 } catch (RemoteException e) {
4127 Slog.e(TAG, "Error communicating with transport for restore");
4128 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4129 mStatus = BackupConstants.TRANSPORT_ERROR;
4130 executeNextState(RestoreState.FINAL);
4131 return;
4132 }
Dan Egnorefe52642009-06-24 00:16:33 -07004133
Christopher Tate2982d062011-09-06 20:35:24 -07004134 // Successful download of the data to be parceled out to the apps, so off we go.
4135 executeNextState(RestoreState.PM_METADATA);
4136 }
4137
4138 void restorePmMetadata() {
4139 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004140 String packageName = mTransport.nextRestorePackage();
4141 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004142 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004143 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004144 mStatus = BackupConstants.TRANSPORT_ERROR;
4145 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004146 return;
4147 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004148 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004149 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004150 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004151 mStatus = BackupConstants.TRANSPORT_OK;
4152 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004153 return;
4154 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004155 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004156 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004157 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004158 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004159 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004160 return;
4161 }
4162
4163 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004164 PackageInfo omPackage = new PackageInfo();
4165 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4166 mPmAgent = new PackageManagerBackupAgent(
4167 mPackageManager, mAgentPackages);
4168 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004169 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004170 // The PM agent called operationComplete() already, because our invocation
4171 // of it is process-local and therefore synchronous. That means that a
4172 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4173 // proceed with running the queue do we remove that pending message and
4174 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004175
Christopher Tate8c032472009-07-02 14:28:47 -07004176 // Verify that the backup set includes metadata. If not, we can't do
4177 // signature/version verification etc, so we simply do not proceed with
4178 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004179 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004180 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004181 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004182 "Package manager restore metadata missing");
4183 mStatus = BackupConstants.TRANSPORT_ERROR;
4184 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4185 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004186 return;
4187 }
Christopher Tate2982d062011-09-06 20:35:24 -07004188 } catch (RemoteException e) {
4189 Slog.e(TAG, "Error communicating with transport for restore");
4190 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4191 mStatus = BackupConstants.TRANSPORT_ERROR;
4192 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4193 executeNextState(RestoreState.FINAL);
4194 return;
4195 }
Christopher Tate8c032472009-07-02 14:28:47 -07004196
Christopher Tate2982d062011-09-06 20:35:24 -07004197 // Metadata is intact, so we can now run the restore queue. If we get here,
4198 // we have already enqueued the necessary next-step message on the looper.
4199 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004200
Christopher Tate2982d062011-09-06 20:35:24 -07004201 void restoreNextAgent() {
4202 try {
4203 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004204
Christopher Tate2982d062011-09-06 20:35:24 -07004205 if (packageName == null) {
4206 Slog.e(TAG, "Error getting next restore package");
4207 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4208 executeNextState(RestoreState.FINAL);
4209 return;
4210 } else if (packageName.equals("")) {
4211 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4212 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4213 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4214 executeNextState(RestoreState.FINAL);
4215 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004216 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004217
4218 if (mObserver != null) {
4219 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004220 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004221 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004222 Slog.d(TAG, "Restore observer died in onUpdate");
4223 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004224 }
4225 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004226
Christopher Tate2982d062011-09-06 20:35:24 -07004227 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4228 if (metaInfo == null) {
4229 Slog.e(TAG, "Missing metadata for " + packageName);
4230 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4231 "Package metadata missing");
4232 executeNextState(RestoreState.RUNNING_QUEUE);
4233 return;
Christopher Tate84725812010-02-04 15:52:40 -08004234 }
4235
Christopher Tate2982d062011-09-06 20:35:24 -07004236 PackageInfo packageInfo;
4237 try {
4238 int flags = PackageManager.GET_SIGNATURES;
4239 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4240 } catch (NameNotFoundException e) {
4241 Slog.e(TAG, "Invalid package restoring data", e);
4242 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4243 "Package missing on device");
4244 executeNextState(RestoreState.RUNNING_QUEUE);
4245 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004246 }
4247
Christopher Tate2982d062011-09-06 20:35:24 -07004248 if (metaInfo.versionCode > packageInfo.versionCode) {
4249 // Data is from a "newer" version of the app than we have currently
4250 // installed. If the app has not declared that it is prepared to
4251 // handle this case, we do not attempt the restore.
4252 if ((packageInfo.applicationInfo.flags
4253 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4254 String message = "Version " + metaInfo.versionCode
4255 + " > installed version " + packageInfo.versionCode;
4256 Slog.w(TAG, "Package " + packageName + ": " + message);
4257 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4258 packageName, message);
4259 executeNextState(RestoreState.RUNNING_QUEUE);
4260 return;
4261 } else {
4262 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4263 + " > installed " + packageInfo.versionCode
4264 + " but restoreAnyVersion");
4265 }
4266 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004267
Christopher Tate2982d062011-09-06 20:35:24 -07004268 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4269 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4270 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4271 "Signature mismatch");
4272 executeNextState(RestoreState.RUNNING_QUEUE);
4273 return;
4274 }
4275
4276 if (DEBUG) Slog.v(TAG, "Package " + packageName
4277 + " restore version [" + metaInfo.versionCode
4278 + "] is compatible with installed version ["
4279 + packageInfo.versionCode + "]");
4280
4281 // Then set up and bind the agent
4282 IBackupAgent agent = bindToAgentSynchronous(
4283 packageInfo.applicationInfo,
4284 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4285 if (agent == null) {
4286 Slog.w(TAG, "Can't find backup agent for " + packageName);
4287 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4288 "Restore agent missing");
4289 executeNextState(RestoreState.RUNNING_QUEUE);
4290 return;
4291 }
4292
4293 // And then finally start the restore on this agent
4294 try {
4295 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4296 ++mCount;
4297 } catch (Exception e) {
4298 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4299 agentErrorCleanup();
4300 executeNextState(RestoreState.RUNNING_QUEUE);
4301 }
4302 } catch (RemoteException e) {
4303 Slog.e(TAG, "Unable to fetch restore data from transport");
4304 mStatus = BackupConstants.TRANSPORT_ERROR;
4305 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004306 }
4307 }
4308
Christopher Tate2982d062011-09-06 20:35:24 -07004309 void finalizeRestore() {
4310 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4311
4312 try {
4313 mTransport.finishRestore();
4314 } catch (RemoteException e) {
4315 Slog.e(TAG, "Error finishing restore", e);
4316 }
4317
4318 if (mObserver != null) {
4319 try {
4320 mObserver.restoreFinished(mStatus);
4321 } catch (RemoteException e) {
4322 Slog.d(TAG, "Restore observer died at restoreFinished");
4323 }
4324 }
4325
4326 // If this was a restoreAll operation, record that this was our
4327 // ancestral dataset, as well as the set of apps that are possibly
4328 // restoreable from the dataset
4329 if (mTargetPackage == null && mPmAgent != null) {
4330 mAncestralPackages = mPmAgent.getRestoredPackages();
4331 mAncestralToken = mToken;
4332 writeRestoreTokens();
4333 }
4334
4335 // We must under all circumstances tell the Package Manager to
4336 // proceed with install notifications if it's waiting for us.
4337 if (mPmToken > 0) {
4338 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4339 try {
4340 mPackageManagerBinder.finishPackageInstall(mPmToken);
4341 } catch (RemoteException e) { /* can't happen */ }
4342 }
4343
4344 // Furthermore we need to reset the session timeout clock
4345 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4346 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4347 TIMEOUT_RESTORE_INTERVAL);
4348
4349 // done; we can finally release the wakelock
4350 Slog.i(TAG, "Restore complete.");
4351 mWakelock.release();
4352 }
4353
4354 // Call asynchronously into the app, passing it the restore data. The next step
4355 // after this is always a callback, either operationComplete() or handleTimeout().
4356 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004357 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004358 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004359 final String packageName = app.packageName;
4360
Christopher Tate2982d062011-09-06 20:35:24 -07004361 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004362
Christopher Tatec7b31e32009-06-10 15:49:30 -07004363 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004364 mBackupDataName = new File(mDataDir, packageName + ".restore");
4365 mNewStateName = new File(mStateDir, packageName + ".new");
4366 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004367
Christopher Tate4a627c72011-04-01 14:43:32 -07004368 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004369 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004370 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004371 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004372 ParcelFileDescriptor.MODE_READ_WRITE |
4373 ParcelFileDescriptor.MODE_CREATE |
4374 ParcelFileDescriptor.MODE_TRUNCATE);
4375
Christopher Tate2982d062011-09-06 20:35:24 -07004376 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004377 // Transport-level failure, so we wind everything up and
4378 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004379 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004380 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004381 mBackupData.close();
4382 mBackupDataName.delete();
4383 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004384 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004385 }
4386
4387 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004388 mBackupData.close();
4389 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004390 ParcelFileDescriptor.MODE_READ_ONLY);
4391
Christopher Tate2982d062011-09-06 20:35:24 -07004392 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004393 ParcelFileDescriptor.MODE_READ_WRITE |
4394 ParcelFileDescriptor.MODE_CREATE |
4395 ParcelFileDescriptor.MODE_TRUNCATE);
4396
Christopher Tate44a27902010-01-27 17:15:49 -08004397 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004398 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4399 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004400 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004401 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004402 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004403 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004404
Christopher Tate2982d062011-09-06 20:35:24 -07004405 // After a restore failure we go back to running the queue. If there
4406 // are no more packages to be restored that will be handled by the
4407 // next step.
4408 executeNextState(RestoreState.RUNNING_QUEUE);
4409 }
4410 }
Chris Tate249345b2010-10-29 12:57:04 -07004411
Christopher Tate2982d062011-09-06 20:35:24 -07004412 void agentErrorCleanup() {
4413 // If the agent fails restore, it might have put the app's data
4414 // into an incoherent state. For consistency we wipe its data
4415 // again in this case before continuing with normal teardown
4416 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4417 agentCleanup();
4418 }
4419
4420 void agentCleanup() {
4421 mBackupDataName.delete();
4422 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4423 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4424 mBackupData = mNewState = null;
4425
4426 // if everything went okay, remember the recorded state now
4427 //
4428 // !!! TODO: the restored data should be migrated on the server
4429 // side into the current dataset. In that case the new state file
4430 // we just created would reflect the data already extant in the
4431 // backend, so there'd be nothing more to do. Until that happens,
4432 // however, we need to make sure that we record the data to the
4433 // current backend dataset. (Yes, this means shipping the data over
4434 // the wire in both directions. That's bad, but consistency comes
4435 // first, then efficiency.) Once we introduce server-side data
4436 // migration to the newly-restored device's dataset, we will change
4437 // the following from a discard of the newly-written state to the
4438 // "correct" operation of renaming into the canonical state blob.
4439 mNewStateName.delete(); // TODO: remove; see above comment
4440 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4441
4442 // If this wasn't the PM pseudopackage, tear down the agent side
4443 if (mCurrentPackage.applicationInfo != null) {
4444 // unbind and tidy up even on timeout or failure
4445 try {
4446 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4447
4448 // The agent was probably running with a stub Application object,
4449 // which isn't a valid run mode for the main app logic. Shut
4450 // down the app so that next time it's launched, it gets the
4451 // usual full initialization. Note that this is only done for
4452 // full-system restores: when a single app has requested a restore,
4453 // it is explicitly not killed following that operation.
4454 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4455 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4456 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4457 + mCurrentPackage.applicationInfo.processName);
4458 mActivityManager.killApplicationProcess(
4459 mCurrentPackage.applicationInfo.processName,
4460 mCurrentPackage.applicationInfo.uid);
4461 }
4462 } catch (RemoteException e) {
4463 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004464 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004465 }
Christopher Tate2982d062011-09-06 20:35:24 -07004466
4467 // The caller is responsible for reestablishing the state machine; our
4468 // responsibility here is to clear the decks for whatever comes next.
4469 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4470 synchronized (mCurrentOpLock) {
4471 mCurrentOperations.clear();
4472 }
4473 }
4474
4475 // A call to agent.doRestore() has been positively acknowledged as complete
4476 @Override
4477 public void operationComplete() {
4478 int size = (int) mBackupDataName.length();
4479 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4480 // Just go back to running the restore queue
4481 agentCleanup();
4482
4483 executeNextState(RestoreState.RUNNING_QUEUE);
4484 }
4485
4486 // A call to agent.doRestore() has timed out
4487 @Override
4488 public void handleTimeout() {
4489 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4490 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4491 mCurrentPackage.packageName, "restore timeout");
4492 // Handle like an agent that threw on invocation: wipe it and go on to the next
4493 agentErrorCleanup();
4494 executeNextState(RestoreState.RUNNING_QUEUE);
4495 }
4496
4497 void executeNextState(RestoreState nextState) {
4498 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4499 + this + " nextState=" + nextState);
4500 mCurrentState = nextState;
4501 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4502 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004503 }
4504 }
4505
Christopher Tate44a27902010-01-27 17:15:49 -08004506 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004507 IBackupTransport mTransport;
4508 PackageInfo mPackage;
4509
Christopher Tate44a27902010-01-27 17:15:49 -08004510 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004511 mTransport = transport;
4512 mPackage = packageInfo;
4513 }
4514
Christopher Tateee0e78a2009-07-02 11:17:03 -07004515 public void run() {
4516 try {
4517 // Clear the on-device backup state to ensure a full backup next time
4518 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4519 File stateFile = new File(stateDir, mPackage.packageName);
4520 stateFile.delete();
4521
4522 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004523 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004524 mTransport.clearBackupData(mPackage);
4525 } catch (RemoteException e) {
4526 // can't happen; the transport is local
4527 } finally {
4528 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004529 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004530 mTransport.finishBackup();
4531 } catch (RemoteException e) {
4532 // can't happen; the transport is local
4533 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004534
4535 // Last but not least, release the cpu
4536 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004537 }
4538 }
4539 }
4540
Christopher Tate44a27902010-01-27 17:15:49 -08004541 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004542 HashSet<String> mQueue;
4543
Christopher Tate44a27902010-01-27 17:15:49 -08004544 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004545 mQueue = transportNames;
4546 }
4547
Christopher Tate4cc86e12009-09-21 19:36:51 -07004548 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004549 try {
4550 for (String transportName : mQueue) {
4551 IBackupTransport transport = getTransport(transportName);
4552 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004553 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004554 continue;
4555 }
4556
Joe Onorato8a9b2202010-02-26 18:56:32 -08004557 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004558 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004559 long startRealtime = SystemClock.elapsedRealtime();
4560 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004561
Christopher Tate4cc86e12009-09-21 19:36:51 -07004562 if (status == BackupConstants.TRANSPORT_OK) {
4563 status = transport.finishBackup();
4564 }
4565
4566 // Okay, the wipe really happened. Clean up our local bookkeeping.
4567 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004568 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004569 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004570 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004571 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004572 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004573 synchronized (mQueueLock) {
4574 recordInitPendingLocked(false, transportName);
4575 }
Dan Egnor726247c2009-09-29 19:12:31 -07004576 } else {
4577 // If this didn't work, requeue this one and try again
4578 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004579 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004580 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004581 synchronized (mQueueLock) {
4582 recordInitPendingLocked(true, transportName);
4583 }
4584 // do this via another alarm to make sure of the wakelock states
4585 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004586 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004587 + transportName + " resched in " + delay);
4588 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4589 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004590 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004591 }
4592 } catch (RemoteException e) {
4593 // can't happen; the transports are local
4594 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004595 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004596 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004597 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004598 mWakelock.release();
4599 }
4600 }
4601 }
4602
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004603 private void dataChangedImpl(String packageName) {
4604 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4605 dataChangedImpl(packageName, targets);
4606 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004607
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004608 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004609 // Record that we need a backup pass for the caller. Since multiple callers
4610 // may share a uid, we need to note all candidates within that uid and schedule
4611 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004612 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004613
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004614 if (targets == null) {
4615 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4616 + " uid=" + Binder.getCallingUid());
4617 return;
4618 }
4619
4620 synchronized (mQueueLock) {
4621 // Note that this client has made data changes that need to be backed up
4622 for (ApplicationInfo app : targets) {
4623 // validate the caller-supplied package name against the known set of
4624 // packages associated with this uid
4625 if (app.packageName.equals(packageName)) {
4626 // Add the caller to the set of pending backups. If there is
4627 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004628 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004629 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004630 // Journal this request in case of crash. The put()
4631 // operation returned null when this package was not already
4632 // in the set; we want to avoid touching the disk redundantly.
4633 writeToJournalLocked(packageName);
4634
Christopher Tatec58efa62011-08-01 19:20:14 -07004635 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004636 int numKeys = mPendingBackups.size();
4637 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4638 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004639 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004640 }
4641 }
4642 }
4643 }
4644 }
4645 }
4646 }
4647
4648 // Note: packageName is currently unused, but may be in the future
4649 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004650 // If the caller does not hold the BACKUP permission, it can only request a
4651 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004652 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004653 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004654 synchronized (mBackupParticipants) {
4655 return mBackupParticipants.get(Binder.getCallingUid());
4656 }
4657 }
4658
4659 // a caller with full permission can ask to back up any participating app
4660 // !!! TODO: allow backup of ANY app?
4661 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4662 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004663 int N = mBackupParticipants.size();
4664 for (int i = 0; i < N; i++) {
4665 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4666 if (s != null) {
4667 targets.addAll(s);
4668 }
4669 }
4670 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004671 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004672 }
Christopher Tate46758122009-05-06 11:22:00 -07004673
Christopher Tatecde87f42009-06-12 12:55:53 -07004674 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004675 RandomAccessFile out = null;
4676 try {
4677 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4678 out = new RandomAccessFile(mJournal, "rws");
4679 out.seek(out.length());
4680 out.writeUTF(str);
4681 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004682 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004683 mJournal = null;
4684 } finally {
4685 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004686 }
4687 }
4688
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004689 // ----- IBackupManager binder interface -----
4690
4691 public void dataChanged(final String packageName) {
4692 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4693 if (targets == null) {
4694 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4695 + " uid=" + Binder.getCallingUid());
4696 return;
4697 }
4698
4699 mBackupHandler.post(new Runnable() {
4700 public void run() {
4701 dataChangedImpl(packageName, targets);
4702 }
4703 });
4704 }
4705
Christopher Tateee0e78a2009-07-02 11:17:03 -07004706 // Clear the given package's backup data from the current transport
4707 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004708 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004709 PackageInfo info;
4710 try {
4711 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4712 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004713 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004714 return;
4715 }
4716
4717 // If the caller does not hold the BACKUP permission, it can only request a
4718 // wipe of its own backed-up data.
4719 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004720 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004721 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4722 apps = mBackupParticipants.get(Binder.getCallingUid());
4723 } else {
4724 // a caller with full permission can ask to back up any participating app
4725 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004726 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004727 apps = new HashSet<ApplicationInfo>();
4728 int N = mBackupParticipants.size();
4729 for (int i = 0; i < N; i++) {
4730 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4731 if (s != null) {
4732 apps.addAll(s);
4733 }
4734 }
4735 }
4736
4737 // now find the given package in the set of candidate apps
4738 for (ApplicationInfo app : apps) {
4739 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004740 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004741 // found it; fire off the clear request
4742 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004743 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004744 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004745 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4746 new ClearParams(getTransport(mCurrentTransport), info));
4747 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004748 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004749 }
4750 break;
4751 }
4752 }
4753 }
4754
Christopher Tateace7f092009-06-15 18:07:25 -07004755 // Run a backup pass immediately for any applications that have declared
4756 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004757 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004759
Joe Onorato8a9b2202010-02-26 18:56:32 -08004760 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004761 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004762 // Because the alarms we are using can jitter, and we want an *immediate*
4763 // backup pass to happen, we restart the timer beginning with "next time,"
4764 // then manually fire the backup trigger intent ourselves.
4765 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004766 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004767 mRunBackupIntent.send();
4768 } catch (PendingIntent.CanceledException e) {
4769 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004770 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004771 }
Christopher Tate46758122009-05-06 11:22:00 -07004772 }
4773 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004774
Christopher Tated2c0cd42011-09-15 15:51:29 -07004775 boolean deviceIsProvisioned() {
4776 final ContentResolver resolver = mContext.getContentResolver();
4777 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4778 }
4779
Christopher Tate4a627c72011-04-01 14:43:32 -07004780 // Run a *full* backup pass for the given package, writing the resulting data stream
4781 // to the supplied file descriptor. This method is synchronous and does not return
4782 // to the caller until the backup has been completed.
4783 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4784 boolean doAllApps, String[] pkgList) {
4785 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4786
4787 // Validate
4788 if (!doAllApps) {
4789 if (!includeShared) {
4790 // If we're backing up shared data (sdcard or equivalent), then we can run
4791 // without any supplied app names. Otherwise, we'd be doing no work, so
4792 // report the error.
4793 if (pkgList == null || pkgList.length == 0) {
4794 throw new IllegalArgumentException(
4795 "Backup requested but neither shared nor any apps named");
4796 }
4797 }
4798 }
4799
Christopher Tate4a627c72011-04-01 14:43:32 -07004800 long oldId = Binder.clearCallingIdentity();
4801 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004802 // Doesn't make sense to do a full backup prior to setup
4803 if (!deviceIsProvisioned()) {
4804 Slog.i(TAG, "Full backup not supported before setup");
4805 return;
4806 }
4807
4808 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4809 + " shared=" + includeShared + " all=" + doAllApps
4810 + " pkgs=" + pkgList);
4811 Slog.i(TAG, "Beginning full backup...");
4812
Christopher Tate4a627c72011-04-01 14:43:32 -07004813 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4814 doAllApps, pkgList);
4815 final int token = generateToken();
4816 synchronized (mFullConfirmations) {
4817 mFullConfirmations.put(token, params);
4818 }
4819
Christopher Tate75a99702011-05-18 16:28:19 -07004820 // start up the confirmation UI
4821 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4822 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4823 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004824 mFullConfirmations.delete(token);
4825 return;
4826 }
Christopher Tate75a99702011-05-18 16:28:19 -07004827
4828 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004829 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4830
4831 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004832 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004833
4834 // wait for the backup to be performed
4835 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4836 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004837 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004838 try {
4839 fd.close();
4840 } catch (IOException e) {
4841 // just eat it
4842 }
Christopher Tate75a99702011-05-18 16:28:19 -07004843 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004844 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07004845 }
Christopher Tate75a99702011-05-18 16:28:19 -07004846 }
4847
4848 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004849 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004850
4851 long oldId = Binder.clearCallingIdentity();
4852
4853 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004854 // Check whether the device has been provisioned -- we don't handle
4855 // full restores prior to completing the setup process.
4856 if (!deviceIsProvisioned()) {
4857 Slog.i(TAG, "Full restore not permitted before setup");
4858 return;
4859 }
4860
4861 Slog.i(TAG, "Beginning full restore...");
4862
Christopher Tate75a99702011-05-18 16:28:19 -07004863 FullRestoreParams params = new FullRestoreParams(fd);
4864 final int token = generateToken();
4865 synchronized (mFullConfirmations) {
4866 mFullConfirmations.put(token, params);
4867 }
4868
4869 // start up the confirmation UI
4870 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4871 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4872 Slog.e(TAG, "Unable to launch full restore confirmation");
4873 mFullConfirmations.delete(token);
4874 return;
4875 }
4876
4877 // make sure the screen is lit for the user interaction
4878 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4879
4880 // start the confirmation countdown
4881 startConfirmationTimeout(token, params);
4882
4883 // wait for the restore to be performed
4884 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4885 waitForCompletion(params);
4886 } finally {
4887 try {
4888 fd.close();
4889 } catch (IOException e) {
4890 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4891 }
4892 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004893 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07004894 }
4895 }
4896
4897 boolean startConfirmationUi(int token, String action) {
4898 try {
4899 Intent confIntent = new Intent(action);
4900 confIntent.setClassName("com.android.backupconfirm",
4901 "com.android.backupconfirm.BackupRestoreConfirmation");
4902 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4903 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4904 mContext.startActivity(confIntent);
4905 } catch (ActivityNotFoundException e) {
4906 return false;
4907 }
4908 return true;
4909 }
4910
4911 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004912 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004913 + TIMEOUT_FULL_CONFIRMATION + " millis");
4914 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4915 token, 0, params);
4916 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004917 }
4918
4919 void waitForCompletion(FullParams params) {
4920 synchronized (params.latch) {
4921 while (params.latch.get() == false) {
4922 try {
4923 params.latch.wait();
4924 } catch (InterruptedException e) { /* never interrupted */ }
4925 }
4926 }
4927 }
4928
4929 void signalFullBackupRestoreCompletion(FullParams params) {
4930 synchronized (params.latch) {
4931 params.latch.set(true);
4932 params.latch.notifyAll();
4933 }
4934 }
4935
4936 // Confirm that the previously-requested full backup/restore operation can proceed. This
4937 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004938 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004939 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004940 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004941 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4942 + " allow=" + allow);
4943
4944 // TODO: possibly require not just this signature-only permission, but even
4945 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004946 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004947
4948 long oldId = Binder.clearCallingIdentity();
4949 try {
4950
4951 FullParams params;
4952 synchronized (mFullConfirmations) {
4953 params = mFullConfirmations.get(token);
4954 if (params != null) {
4955 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4956 mFullConfirmations.delete(token);
4957
4958 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004959 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004960 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004961 : MSG_RUN_FULL_RESTORE;
4962
Christopher Tate728a1c42011-07-28 18:03:03 -07004963 params.observer = observer;
4964 params.curPassword = curPassword;
4965 params.encryptPassword = encPpassword;
4966
Christopher Tate75a99702011-05-18 16:28:19 -07004967 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004968 mWakelock.acquire();
4969 Message msg = mBackupHandler.obtainMessage(verb, params);
4970 mBackupHandler.sendMessage(msg);
4971 } else {
4972 Slog.w(TAG, "User rejected full backup/restore operation");
4973 // indicate completion without having actually transferred any data
4974 signalFullBackupRestoreCompletion(params);
4975 }
4976 } else {
4977 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4978 }
4979 }
4980 } finally {
4981 Binder.restoreCallingIdentity(oldId);
4982 }
4983 }
4984
Christopher Tate8031a3d2009-07-06 16:36:05 -07004985 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004986 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004988 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004989
Joe Onorato8a9b2202010-02-26 18:56:32 -08004990 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004991
Christopher Tate6ef58a12009-06-29 14:56:28 -07004992 boolean wasEnabled = mEnabled;
4993 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004994 Settings.Secure.putInt(mContext.getContentResolver(),
4995 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004996 mEnabled = enable;
4997 }
4998
Christopher Tate49401dd2009-07-01 12:34:29 -07004999 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005000 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005001 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005002 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005003 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005004 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005005 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005006
Christopher Tateb6787f22009-07-02 17:40:45 -07005007 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005008
5009 // This also constitutes an opt-out, so we wipe any data for
5010 // this device from the backend. We start that process with
5011 // an alarm in order to guarantee wakelock states.
5012 if (wasEnabled && mProvisioned) {
5013 // NOTE: we currently flush every registered transport, not just
5014 // the currently-active one.
5015 HashSet<String> allTransports;
5016 synchronized (mTransports) {
5017 allTransports = new HashSet<String>(mTransports.keySet());
5018 }
5019 // build the set of transports for which we are posting an init
5020 for (String transport : allTransports) {
5021 recordInitPendingLocked(true, transport);
5022 }
5023 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5024 mRunInitIntent);
5025 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005026 }
5027 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005028 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005029
Christopher Tatecce9da52010-02-03 15:11:15 -08005030 // Enable/disable automatic restore of app data at install time
5031 public void setAutoRestore(boolean doAutoRestore) {
5032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005033 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005034
Joe Onorato8a9b2202010-02-26 18:56:32 -08005035 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005036
5037 synchronized (this) {
5038 Settings.Secure.putInt(mContext.getContentResolver(),
5039 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5040 mAutoRestore = doAutoRestore;
5041 }
5042 }
5043
Christopher Tate8031a3d2009-07-06 16:36:05 -07005044 // Mark the backup service as having been provisioned
5045 public void setBackupProvisioned(boolean available) {
5046 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5047 "setBackupProvisioned");
5048
5049 boolean wasProvisioned = mProvisioned;
5050 synchronized (this) {
5051 Settings.Secure.putInt(mContext.getContentResolver(),
5052 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5053 mProvisioned = available;
5054 }
5055
5056 synchronized (mQueueLock) {
5057 if (available && !wasProvisioned && mEnabled) {
5058 // we're now good to go, so start the backup alarms
5059 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5060 } else if (!available) {
5061 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005062 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005063 mAlarmManager.cancel(mRunBackupIntent);
5064 }
5065 }
5066 }
5067
5068 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005069 // We used to use setInexactRepeating(), but that may be linked to
5070 // backups running at :00 more often than not, creating load spikes.
5071 // Schedule at an exact time for now, and also add a bit of "fuzz".
5072
5073 Random random = new Random();
5074 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5075 random.nextInt(FUZZ_MILLIS);
5076 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5077 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005078 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005079 }
5080
Christopher Tate6ef58a12009-06-29 14:56:28 -07005081 // Report whether the backup mechanism is currently enabled
5082 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005084 return mEnabled; // no need to synchronize just to read it
5085 }
5086
Christopher Tate91717492009-06-26 21:07:13 -07005087 // Report the name of the currently active transport
5088 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005089 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005090 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005091 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005092 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005093 }
5094
Christopher Tate91717492009-06-26 21:07:13 -07005095 // Report all known, available backup transports
5096 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005097 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005098
Christopher Tate91717492009-06-26 21:07:13 -07005099 String[] list = null;
5100 ArrayList<String> known = new ArrayList<String>();
5101 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5102 if (entry.getValue() != null) {
5103 known.add(entry.getKey());
5104 }
5105 }
5106
5107 if (known.size() > 0) {
5108 list = new String[known.size()];
5109 known.toArray(list);
5110 }
5111 return list;
5112 }
5113
5114 // Select which transport to use for the next backup operation. If the given
5115 // name is not one of the available transports, no action is taken and the method
5116 // returns null.
5117 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005118 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005119
5120 synchronized (mTransports) {
5121 String prevTransport = null;
5122 if (mTransports.get(transport) != null) {
5123 prevTransport = mCurrentTransport;
5124 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005125 Settings.Secure.putString(mContext.getContentResolver(),
5126 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005127 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005128 + " returning " + prevTransport);
5129 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005130 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005131 }
5132 return prevTransport;
5133 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005134 }
5135
Christopher Tatef5e1c292010-12-08 18:40:26 -08005136 // Supply the configuration Intent for the given transport. If the name is not one
5137 // of the available transports, or if the transport does not supply any configuration
5138 // UI, the method returns null.
5139 public Intent getConfigurationIntent(String transportName) {
5140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5141 "getConfigurationIntent");
5142
5143 synchronized (mTransports) {
5144 final IBackupTransport transport = mTransports.get(transportName);
5145 if (transport != null) {
5146 try {
5147 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005148 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005149 + intent);
5150 return intent;
5151 } catch (RemoteException e) {
5152 /* fall through to return null */
5153 }
5154 }
5155 }
5156
5157 return null;
5158 }
5159
5160 // Supply the configuration summary string for the given transport. If the name is
5161 // not one of the available transports, or if the transport does not supply any
5162 // summary / destination string, the method can return null.
5163 //
5164 // This string is used VERBATIM as the summary text of the relevant Settings item!
5165 public String getDestinationString(String transportName) {
5166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005167 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005168
5169 synchronized (mTransports) {
5170 final IBackupTransport transport = mTransports.get(transportName);
5171 if (transport != null) {
5172 try {
5173 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005174 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005175 return text;
5176 } catch (RemoteException e) {
5177 /* fall through to return null */
5178 }
5179 }
5180 }
5181
5182 return null;
5183 }
5184
Christopher Tate043dadc2009-06-02 16:11:00 -07005185 // Callback: a requested backup agent has been instantiated. This should only
5186 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005187 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005188 synchronized(mAgentConnectLock) {
5189 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005190 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005191 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5192 mConnectedAgent = agent;
5193 mConnecting = false;
5194 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005195 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005196 + " claiming agent connected");
5197 }
5198 mAgentConnectLock.notifyAll();
5199 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005200 }
5201
5202 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5203 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005204 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005205 public void agentDisconnected(String packageName) {
5206 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005207 synchronized(mAgentConnectLock) {
5208 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5209 mConnectedAgent = null;
5210 mConnecting = false;
5211 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005212 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005213 + " claiming agent disconnected");
5214 }
5215 mAgentConnectLock.notifyAll();
5216 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005217 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005218
Christopher Tate1bb69062010-02-19 17:02:12 -08005219 // An application being installed will need a restore pass, then the Package Manager
5220 // will need to be told when the restore is finished.
5221 public void restoreAtInstall(String packageName, int token) {
5222 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005223 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005224 + " attemping install-time restore");
5225 return;
5226 }
5227
5228 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005229 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005230 + " token=" + Integer.toHexString(token));
5231
Christopher Tatef0872722010-02-25 15:22:48 -08005232 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005233 // okay, we're going to attempt a restore of this package from this restore set.
5234 // The eventual message back into the Package Manager to run the post-install
5235 // steps for 'token' will be issued from the restore handling code.
5236
5237 // We can use a synthetic PackageInfo here because:
5238 // 1. We know it's valid, since the Package Manager supplied the name
5239 // 2. Only the packageName field will be used by the restore code
5240 PackageInfo pkg = new PackageInfo();
5241 pkg.packageName = packageName;
5242
5243 mWakelock.acquire();
5244 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5245 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005246 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005247 mBackupHandler.sendMessage(msg);
5248 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005249 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5250 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005251 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005252 try {
5253 mPackageManagerBinder.finishPackageInstall(token);
5254 } catch (RemoteException e) { /* can't happen */ }
5255 }
5256 }
5257
Christopher Tate8c850b72009-06-07 19:33:20 -07005258 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005259 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5260 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5261 + " transport=" + transport);
5262
5263 boolean needPermission = true;
5264 if (transport == null) {
5265 transport = mCurrentTransport;
5266
5267 if (packageName != null) {
5268 PackageInfo app = null;
5269 try {
5270 app = mPackageManager.getPackageInfo(packageName, 0);
5271 } catch (NameNotFoundException nnf) {
5272 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5273 throw new IllegalArgumentException("Package " + packageName + " not found");
5274 }
5275
5276 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5277 // So: using the current active transport, and the caller has asked
5278 // that its own package will be restored. In this narrow use case
5279 // we do not require the caller to hold the permission.
5280 needPermission = false;
5281 }
5282 }
5283 }
5284
5285 if (needPermission) {
5286 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5287 "beginRestoreSession");
5288 } else {
5289 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5290 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005291
5292 synchronized(this) {
5293 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005294 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005295 return null;
5296 }
Chris Tate44ab8452010-11-16 15:10:49 -08005297 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005298 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005299 }
5300 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005301 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005302
Christopher Tate73a3cb32010-12-13 18:27:26 -08005303 void clearRestoreSession(ActiveRestoreSession currentSession) {
5304 synchronized(this) {
5305 if (currentSession != mActiveRestoreSession) {
5306 Slog.e(TAG, "ending non-current restore session");
5307 } else {
5308 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5309 mActiveRestoreSession = null;
5310 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5311 }
5312 }
5313 }
5314
Christopher Tate44a27902010-01-27 17:15:49 -08005315 // Note that a currently-active backup agent has notified us that it has
5316 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005317 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005318 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005319 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5320 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005321 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005322 op = mCurrentOperations.get(token);
5323 if (op != null) {
5324 op.state = OP_ACKNOWLEDGED;
5325 }
Christopher Tate44a27902010-01-27 17:15:49 -08005326 mCurrentOpLock.notifyAll();
5327 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005328
5329 // The completion callback, if any, is invoked on the handler
5330 if (op != null && op.callback != null) {
5331 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5332 mBackupHandler.sendMessage(msg);
5333 }
Christopher Tate44a27902010-01-27 17:15:49 -08005334 }
5335
Christopher Tate9b3905c2009-06-08 15:24:01 -07005336 // ----- Restore session -----
5337
Christopher Tate80202c82010-01-25 19:37:47 -08005338 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005339 private static final String TAG = "RestoreSession";
5340
Chris Tate44ab8452010-11-16 15:10:49 -08005341 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005342 private IBackupTransport mRestoreTransport = null;
5343 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005344 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005345
Chris Tate44ab8452010-11-16 15:10:49 -08005346 ActiveRestoreSession(String packageName, String transport) {
5347 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005348 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005349 }
5350
5351 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005352 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005354 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005355 if (observer == null) {
5356 throw new IllegalArgumentException("Observer must not be null");
5357 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005358
Christopher Tate73a3cb32010-12-13 18:27:26 -08005359 if (mEnded) {
5360 throw new IllegalStateException("Restore session already ended");
5361 }
5362
Christopher Tate1bb69062010-02-19 17:02:12 -08005363 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005364 try {
Christopher Tate43383042009-07-13 15:17:13 -07005365 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005366 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005367 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005368 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005369 // spin off the transport request to our service thread
5370 mWakelock.acquire();
5371 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5372 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5373 mBackupHandler.sendMessage(msg);
5374 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005375 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005376 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005377 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005378 } finally {
5379 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005380 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005381 }
5382
Christopher Tate84725812010-02-04 15:52:40 -08005383 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005384 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5385 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005386
Chris Tate44ab8452010-11-16 15:10:49 -08005387 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005388 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005389
Christopher Tate73a3cb32010-12-13 18:27:26 -08005390 if (mEnded) {
5391 throw new IllegalStateException("Restore session already ended");
5392 }
5393
Dan Egnor0084da52009-07-29 12:57:16 -07005394 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005395 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5396 return -1;
5397 }
5398
5399 if (mPackageName != null) {
5400 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005401 return -1;
5402 }
5403
Christopher Tate21ab6a52009-09-24 18:01:46 -07005404 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005405 for (int i = 0; i < mRestoreSets.length; i++) {
5406 if (token == mRestoreSets[i].token) {
5407 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005408 mWakelock.acquire();
5409 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005410 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005411 mBackupHandler.sendMessage(msg);
5412 Binder.restoreCallingIdentity(oldId);
5413 return 0;
5414 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005415 }
5416 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005417
Joe Onorato8a9b2202010-02-26 18:56:32 -08005418 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005419 return -1;
5420 }
5421
Christopher Tate284f1bb2011-07-07 14:31:18 -07005422 public synchronized int restoreSome(long token, IRestoreObserver observer,
5423 String[] packages) {
5424 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5425 "performRestore");
5426
5427 if (DEBUG) {
5428 StringBuilder b = new StringBuilder(128);
5429 b.append("restoreSome token=");
5430 b.append(Long.toHexString(token));
5431 b.append(" observer=");
5432 b.append(observer.toString());
5433 b.append(" packages=");
5434 if (packages == null) {
5435 b.append("null");
5436 } else {
5437 b.append('{');
5438 boolean first = true;
5439 for (String s : packages) {
5440 if (!first) {
5441 b.append(", ");
5442 } else first = false;
5443 b.append(s);
5444 }
5445 b.append('}');
5446 }
5447 Slog.d(TAG, b.toString());
5448 }
5449
5450 if (mEnded) {
5451 throw new IllegalStateException("Restore session already ended");
5452 }
5453
5454 if (mRestoreTransport == null || mRestoreSets == null) {
5455 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5456 return -1;
5457 }
5458
5459 if (mPackageName != null) {
5460 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5461 return -1;
5462 }
5463
5464 synchronized (mQueueLock) {
5465 for (int i = 0; i < mRestoreSets.length; i++) {
5466 if (token == mRestoreSets[i].token) {
5467 long oldId = Binder.clearCallingIdentity();
5468 mWakelock.acquire();
5469 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5470 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5471 packages, true);
5472 mBackupHandler.sendMessage(msg);
5473 Binder.restoreCallingIdentity(oldId);
5474 return 0;
5475 }
5476 }
5477 }
5478
5479 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5480 return -1;
5481 }
5482
Christopher Tate84725812010-02-04 15:52:40 -08005483 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005484 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005485
Christopher Tate73a3cb32010-12-13 18:27:26 -08005486 if (mEnded) {
5487 throw new IllegalStateException("Restore session already ended");
5488 }
5489
Chris Tate44ab8452010-11-16 15:10:49 -08005490 if (mPackageName != null) {
5491 if (! mPackageName.equals(packageName)) {
5492 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5493 + " on session for package " + mPackageName);
5494 return -1;
5495 }
5496 }
5497
Christopher Tate84725812010-02-04 15:52:40 -08005498 PackageInfo app = null;
5499 try {
5500 app = mPackageManager.getPackageInfo(packageName, 0);
5501 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005502 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005503 return -1;
5504 }
5505
5506 // If the caller is not privileged and is not coming from the target
5507 // app's uid, throw a permission exception back to the caller.
5508 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5509 Binder.getCallingPid(), Binder.getCallingUid());
5510 if ((perm == PackageManager.PERMISSION_DENIED) &&
5511 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005512 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005513 + " or calling uid=" + Binder.getCallingUid());
5514 throw new SecurityException("No permission to restore other packages");
5515 }
5516
Christopher Tate7d411a32010-02-26 11:27:08 -08005517 // If the package has no backup agent, we obviously cannot proceed
5518 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005519 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005520 return -1;
5521 }
5522
Christopher Tate84725812010-02-04 15:52:40 -08005523 // So far so good; we're allowed to try to restore this package. Now
5524 // check whether there is data for it in the current dataset, falling back
5525 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005526 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005527
5528 // If we didn't come up with a place to look -- no ancestral dataset and
5529 // the app has never been backed up from this device -- there's nothing
5530 // to do but return failure.
5531 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005532 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005533 return -1;
5534 }
5535
5536 // Ready to go: enqueue the restore request and claim success
5537 long oldId = Binder.clearCallingIdentity();
5538 mWakelock.acquire();
5539 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005540 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005541 mBackupHandler.sendMessage(msg);
5542 Binder.restoreCallingIdentity(oldId);
5543 return 0;
5544 }
5545
Christopher Tate73a3cb32010-12-13 18:27:26 -08005546 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5547 class EndRestoreRunnable implements Runnable {
5548 BackupManagerService mBackupManager;
5549 ActiveRestoreSession mSession;
5550
5551 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5552 mBackupManager = manager;
5553 mSession = session;
5554 }
5555
5556 public void run() {
5557 // clean up the session's bookkeeping
5558 synchronized (mSession) {
5559 try {
5560 if (mSession.mRestoreTransport != null) {
5561 mSession.mRestoreTransport.finishRestore();
5562 }
5563 } catch (Exception e) {
5564 Slog.e(TAG, "Error in finishRestore", e);
5565 } finally {
5566 mSession.mRestoreTransport = null;
5567 mSession.mEnded = true;
5568 }
5569 }
5570
5571 // clean up the BackupManagerService side of the bookkeeping
5572 // and cancel any pending timeout message
5573 mBackupManager.clearRestoreSession(mSession);
5574 }
5575 }
5576
Dan Egnor0084da52009-07-29 12:57:16 -07005577 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005578 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005579
Christopher Tate73a3cb32010-12-13 18:27:26 -08005580 if (mEnded) {
5581 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005582 }
5583
Christopher Tate73a3cb32010-12-13 18:27:26 -08005584 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005585 }
5586 }
5587
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005588 @Override
5589 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005590 long identityToken = Binder.clearCallingIdentity();
5591 try {
5592 dumpInternal(pw);
5593 } finally {
5594 Binder.restoreCallingIdentity(identityToken);
5595 }
5596 }
5597
5598 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005599 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005600 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005601 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005602 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005603 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005604 pw.println("Last backup pass: " + mLastBackupPass
5605 + " (now = " + System.currentTimeMillis() + ')');
5606 pw.println(" next scheduled: " + mNextBackupPass);
5607
Christopher Tate91717492009-06-26 21:07:13 -07005608 pw.println("Available transports:");
5609 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005610 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5611 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005612 IBackupTransport transport = getTransport(t);
5613 File dir = new File(mBaseStateDir, transport.transportDirName());
5614 pw.println(" destination: " + transport.currentDestinationString());
5615 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005616 for (File f : dir.listFiles()) {
5617 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5618 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005619 } catch (Exception e) {
5620 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005621 pw.println(" Error: " + e);
5622 }
Christopher Tate91717492009-06-26 21:07:13 -07005623 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005624
5625 pw.println("Pending init: " + mPendingInits.size());
5626 for (String s : mPendingInits) {
5627 pw.println(" " + s);
5628 }
5629
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005630 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005631 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005632 for (int i=0; i<N; i++) {
5633 int uid = mBackupParticipants.keyAt(i);
5634 pw.print(" uid: ");
5635 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005636 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5637 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005638 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005639 }
5640 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005641
Christopher Tateb49ceb32010-02-08 16:22:24 -08005642 pw.println("Ancestral packages: "
5643 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005644 if (mAncestralPackages != null) {
5645 for (String pkg : mAncestralPackages) {
5646 pw.println(" " + pkg);
5647 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005648 }
5649
Christopher Tate73e02522009-07-15 14:18:26 -07005650 pw.println("Ever backed up: " + mEverStoredApps.size());
5651 for (String pkg : mEverStoredApps) {
5652 pw.println(" " + pkg);
5653 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005654
5655 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005656 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005657 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005658 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005659 }
5660 }
Christopher Tate487529a2009-04-29 14:03:25 -07005661}