blob: 9f01ecae36b6ab022de6923b0142cf75143a7b42 [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 Tate97ea1222012-05-17 14:59:41 -070051import android.database.ContentObserver;
Christopher Tate3799bc22009-05-06 16:13:56 -070052import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070054import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070055import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080060import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070062import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070063import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070064import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.os.RemoteException;
Christopher Tate32418be2011-10-10 13:51:12 -070066import android.os.ServiceManager;
Dan Egnorbb9001c2009-07-27 12:20:13 -070067import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070069import android.os.WorkSource;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070070import android.os.Environment.UserEnvironment;
Christopher Tate32418be2011-10-10 13:51:12 -070071import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080072import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070073import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070074import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080075import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070076import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070077import android.util.StringBuilderPrinter;
78
Jason parksa3cdaa52011-01-13 14:15:43 -060079import com.android.internal.backup.BackupConstants;
80import com.android.internal.backup.IBackupTransport;
81import com.android.internal.backup.LocalTransport;
82import com.android.server.PackageManagerBackupAgent.Metadata;
83
Christopher Tate2efd2db2011-07-19 16:32:49 -070084import java.io.BufferedInputStream;
85import java.io.BufferedOutputStream;
86import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070087import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070088import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070089import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070090import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070091import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070092import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080093import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070094import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070095import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070096import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070097import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070098import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070099import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700100import java.security.InvalidAlgorithmParameterException;
101import java.security.InvalidKeyException;
102import java.security.Key;
103import java.security.NoSuchAlgorithmException;
104import java.security.SecureRandom;
105import java.security.spec.InvalidKeySpecException;
106import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700107import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400108import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700109import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700110import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400111import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700112import java.util.HashSet;
113import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700114import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700115import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800116import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700117import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700118import java.util.zip.Deflater;
119import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700120import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700121
Christopher Tate2efd2db2011-07-19 16:32:49 -0700122import javax.crypto.BadPaddingException;
123import javax.crypto.Cipher;
124import javax.crypto.CipherInputStream;
125import javax.crypto.CipherOutputStream;
126import javax.crypto.IllegalBlockSizeException;
127import javax.crypto.NoSuchPaddingException;
128import javax.crypto.SecretKey;
129import javax.crypto.SecretKeyFactory;
130import javax.crypto.spec.IvParameterSpec;
131import javax.crypto.spec.PBEKeySpec;
132import javax.crypto.spec.SecretKeySpec;
133
Christopher Tate487529a2009-04-29 14:03:25 -0700134class BackupManagerService extends IBackupManager.Stub {
135 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700136 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700137 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700138
139 // Name and current contents version of the full-backup manifest file
140 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
141 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700142 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
143 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700144 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700145
Christopher Tate73d73692012-01-20 17:11:31 -0800146 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
147
Christopher Tate49401dd2009-07-01 12:34:29 -0700148 // How often we perform a backup pass. Privileged external callers can
149 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700150 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700151
Dan Egnorc1c49c02009-10-30 17:35:39 -0700152 // Random variation in backup scheduling time to avoid server load spikes
153 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
154
Christopher Tate8031a3d2009-07-06 16:36:05 -0700155 // The amount of time between the initial provisioning of the device and
156 // the first backup pass.
157 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
158
Christopher Tate45281862010-03-05 15:46:30 -0800159 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
160 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
161 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700162 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700163 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700164 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700165 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700166 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700167 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
168 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800169 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700170 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
171 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700172
Christopher Tate8e294d42011-08-31 20:37:12 -0700173 // backup task state machine tick
174 static final int MSG_BACKUP_RESTORE_STEP = 20;
175 static final int MSG_OP_COMPLETE = 21;
176
Christopher Tatec7b31e32009-06-10 15:49:30 -0700177 // Timeout interval for deciding that a bind or clear-data has taken too long
178 static final long TIMEOUT_INTERVAL = 10 * 1000;
179
Christopher Tate44a27902010-01-27 17:15:49 -0800180 // Timeout intervals for agent backup & restore operations
181 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700182 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700183 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800184 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
185
Christopher Tate2efd2db2011-07-19 16:32:49 -0700186 // User confirmation timeout for a full backup/restore operation. It's this long in
187 // order to give them time to enter the backup password.
188 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700189
Christopher Tate487529a2009-04-29 14:03:25 -0700190 private Context mContext;
191 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800192 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700193 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700194 private PowerManager mPowerManager;
195 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700196 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800197 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700198
Christopher Tate73e02522009-07-15 14:18:26 -0700199 boolean mEnabled; // access to this is synchronized on 'this'
200 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800201 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700202 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800203 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800204 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700205 PendingIntent mRunBackupIntent, mRunInitIntent;
206 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700207 // map UIDs to the set of participating packages under that UID
208 final SparseArray<HashSet<String>> mBackupParticipants
209 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700210 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700211 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700212 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700213
Christopher Tatecc55f812011-08-16 16:06:53 -0700214 BackupRequest(String pkgName) {
215 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700216 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700217
218 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700219 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700220 }
Christopher Tate46758122009-05-06 11:22:00 -0700221 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800222 // Backups that we haven't started yet. Keys are package names.
223 HashMap<String,BackupRequest> mPendingBackups
224 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700225
226 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700227 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700228
229 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700230 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700231
Christopher Tate043dadc2009-06-02 16:11:00 -0700232 // The thread performing the sequence of queued backups binds to each app's agent
233 // in succession. Bind notifications are asynchronously delivered through the
234 // Activity Manager; use this lock object to signal when a requested binding has
235 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700236 final Object mAgentConnectLock = new Object();
237 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700238 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700239 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700240 volatile long mLastBackupPass;
241 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700242
Christopher Tate6de74ff2012-01-17 15:20:32 -0800243 // For debugging, we maintain a progress trace of operations during backup
244 static final boolean DEBUG_BACKUP_TRACE = true;
245 final List<String> mBackupTrace = new ArrayList<String>();
246
Christopher Tate55f931a2009-09-29 17:17:34 -0700247 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700248 final Object mClearDataLock = new Object();
249 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700250
Christopher Tate91717492009-06-26 21:07:13 -0700251 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700252 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700253 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700254 String mCurrentTransport;
255 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800256 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700257
Christopher Tate97ea1222012-05-17 14:59:41 -0700258 // Watch the device provisioning operation during setup
259 ContentObserver mProvisionedObserver;
260
261 class ProvisionedObserver extends ContentObserver {
262 public ProvisionedObserver(Handler handler) {
263 super(handler);
264 }
265
266 public void onChange(boolean selfChange) {
267 final boolean wasProvisioned = mProvisioned;
268 final boolean isProvisioned = deviceIsProvisioned();
269 // latch: never unprovision
270 mProvisioned = wasProvisioned || isProvisioned;
271 if (MORE_DEBUG) {
272 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
273 + " is=" + isProvisioned + " now=" + mProvisioned);
274 }
275
276 synchronized (mQueueLock) {
277 if (mProvisioned && !wasProvisioned && mEnabled) {
278 // we're now good to go, so start the backup alarms
279 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
280 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
281 }
282 }
283 }
284 }
285
Christopher Tate2d449afe2010-03-29 19:14:24 -0700286 class RestoreGetSetsParams {
287 public IBackupTransport transport;
288 public ActiveRestoreSession session;
289 public IRestoreObserver observer;
290
291 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
292 IRestoreObserver _observer) {
293 transport = _transport;
294 session = _session;
295 observer = _observer;
296 }
297 }
298
Christopher Tate73e02522009-07-15 14:18:26 -0700299 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700300 public IBackupTransport transport;
301 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700302 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800303 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800304 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700305 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700306 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800307
308 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700309 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800310 transport = _transport;
311 observer = _obs;
312 token = _token;
313 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800314 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700315 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700316 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800317 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700318
Chris Tate249345b2010-10-29 12:57:04 -0700319 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
320 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700321 transport = _transport;
322 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700323 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800324 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800325 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700326 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700327 filterSet = null;
328 }
329
330 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
331 String[] _filterSet, boolean _needFullBackup) {
332 transport = _transport;
333 observer = _obs;
334 token = _token;
335 pkgInfo = null;
336 pmToken = 0;
337 needFullBackup = _needFullBackup;
338 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700339 }
340 }
341
Christopher Tate73e02522009-07-15 14:18:26 -0700342 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700343 public IBackupTransport transport;
344 public PackageInfo packageInfo;
345
346 ClearParams(IBackupTransport _transport, PackageInfo _info) {
347 transport = _transport;
348 packageInfo = _info;
349 }
350 }
351
Christopher Tate4a627c72011-04-01 14:43:32 -0700352 class FullParams {
353 public ParcelFileDescriptor fd;
354 public final AtomicBoolean latch;
355 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700356 public String curPassword; // filled in by the confirmation step
357 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700358
359 FullParams() {
360 latch = new AtomicBoolean(false);
361 }
362 }
363
364 class FullBackupParams extends FullParams {
365 public boolean includeApks;
366 public boolean includeShared;
367 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700368 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700369 public String[] packages;
370
371 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700372 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700373 fd = output;
374 includeApks = saveApks;
375 includeShared = saveShared;
376 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700377 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700378 packages = pkgList;
379 }
380 }
381
382 class FullRestoreParams extends FullParams {
383 FullRestoreParams(ParcelFileDescriptor input) {
384 fd = input;
385 }
386 }
387
Christopher Tate44a27902010-01-27 17:15:49 -0800388 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
389 // token is the index of the entry in the pending-operations list.
390 static final int OP_PENDING = 0;
391 static final int OP_ACKNOWLEDGED = 1;
392 static final int OP_TIMEOUT = -1;
393
Christopher Tate8e294d42011-08-31 20:37:12 -0700394 class Operation {
395 public int state;
396 public BackupRestoreTask callback;
397
398 Operation(int initialState, BackupRestoreTask callbackObj) {
399 state = initialState;
400 callback = callbackObj;
401 }
402 }
403 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800404 final Object mCurrentOpLock = new Object();
405 final Random mTokenGenerator = new Random();
406
Christopher Tate4a627c72011-04-01 14:43:32 -0700407 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
408
Christopher Tate5cb400b2009-06-25 16:03:14 -0700409 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700410 File mBaseStateDir;
411 File mDataDir;
412 File mJournalDir;
413 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700414
Christopher Tate2efd2db2011-07-19 16:32:49 -0700415 // Backup password, if any, and the file where it's saved. What is stored is not the
416 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
417 // persisted) salt. Validation is performed by running the challenge text through the
418 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
419 // the saved hash string, then the challenge text matches the originally supplied
420 // password text.
421 private final SecureRandom mRng = new SecureRandom();
422 private String mPasswordHash;
423 private File mPasswordHashFile;
424 private byte[] mPasswordSalt;
425
426 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
427 static final int PBKDF2_HASH_ROUNDS = 10000;
428 static final int PBKDF2_KEY_SIZE = 256; // bits
429 static final int PBKDF2_SALT_SIZE = 512; // bits
430 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
431
Christopher Tate84725812010-02-04 15:52:40 -0800432 // Keep a log of all the apps we've ever backed up, and what the
433 // dataset tokens are for both the current backup dataset and
434 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700435 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700436 HashSet<String> mEverStoredApps = new HashSet<String>();
437
Christopher Tateb49ceb32010-02-08 16:22:24 -0800438 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800439 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800440 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800441 long mAncestralToken = 0;
442 long mCurrentToken = 0;
443
Christopher Tate4cc86e12009-09-21 19:36:51 -0700444 // Persistently track the need to do a full init
445 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
446 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700447
Christopher Tate4a627c72011-04-01 14:43:32 -0700448 // Utility: build a new random integer token
449 int generateToken() {
450 int token;
451 do {
452 synchronized (mTokenGenerator) {
453 token = mTokenGenerator.nextInt();
454 }
455 } while (token < 0);
456 return token;
457 }
458
Christopher Tate44a27902010-01-27 17:15:49 -0800459 // ----- Asynchronous backup/restore handler thread -----
460
461 private class BackupHandler extends Handler {
462 public BackupHandler(Looper looper) {
463 super(looper);
464 }
465
466 public void handleMessage(Message msg) {
467
468 switch (msg.what) {
469 case MSG_RUN_BACKUP:
470 {
471 mLastBackupPass = System.currentTimeMillis();
472 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
473
474 IBackupTransport transport = getTransport(mCurrentTransport);
475 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800476 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700477 synchronized (mQueueLock) {
478 mBackupRunning = false;
479 }
Christopher Tate44a27902010-01-27 17:15:49 -0800480 mWakelock.release();
481 break;
482 }
483
484 // snapshot the pending-backup set and work on that
485 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800486 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800487 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800488 // Do we have any work to do? Construct the work queue
489 // then release the synchronization lock to actually run
490 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800491 if (mPendingBackups.size() > 0) {
492 for (BackupRequest b: mPendingBackups.values()) {
493 queue.add(b);
494 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800495 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800496 mPendingBackups.clear();
497
498 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800499 mJournal = null;
500
Christopher Tate44a27902010-01-27 17:15:49 -0800501 }
502 }
Christopher Tatec61da312010-02-05 10:41:27 -0800503
Christopher Tate8e294d42011-08-31 20:37:12 -0700504 // At this point, we have started a new journal file, and the old
505 // file identity is being passed to the backup processing task.
506 // When it completes successfully, that old journal file will be
507 // deleted. If we crash prior to that, the old journal is parsed
508 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800509 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700510 // Spin up a backup state sequence and set it running
511 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
512 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
513 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800514 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800515 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700516 synchronized (mQueueLock) {
517 mBackupRunning = false;
518 }
Christopher Tatec61da312010-02-05 10:41:27 -0800519 mWakelock.release();
520 }
Christopher Tate44a27902010-01-27 17:15:49 -0800521 break;
522 }
523
Christopher Tate8e294d42011-08-31 20:37:12 -0700524 case MSG_BACKUP_RESTORE_STEP:
525 {
526 try {
527 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
528 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
529 task.execute();
530 } catch (ClassCastException e) {
531 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
532 }
533 break;
534 }
535
536 case MSG_OP_COMPLETE:
537 {
538 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700539 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
540 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700541 } catch (ClassCastException e) {
542 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
543 }
544 break;
545 }
546
Christopher Tate44a27902010-01-27 17:15:49 -0800547 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700548 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700549 // TODO: refactor full backup to be a looper-based state machine
550 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700551 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700552 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
553 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700554 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700555 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700556 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800557 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700558 }
Christopher Tate44a27902010-01-27 17:15:49 -0800559
560 case MSG_RUN_RESTORE:
561 {
562 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800563 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700564 PerformRestoreTask task = new PerformRestoreTask(
565 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700566 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700567 params.needFullBackup, params.filterSet);
568 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
569 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800570 break;
571 }
572
Christopher Tate75a99702011-05-18 16:28:19 -0700573 case MSG_RUN_FULL_RESTORE:
574 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700575 // TODO: refactor full restore to be a looper-based state machine
576 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700577 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700578 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
579 params.curPassword, params.encryptPassword,
580 params.observer, params.latch);
581 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700582 break;
583 }
584
Christopher Tate44a27902010-01-27 17:15:49 -0800585 case MSG_RUN_CLEAR:
586 {
587 ClearParams params = (ClearParams)msg.obj;
588 (new PerformClearTask(params.transport, params.packageInfo)).run();
589 break;
590 }
591
592 case MSG_RUN_INITIALIZE:
593 {
594 HashSet<String> queue;
595
596 // Snapshot the pending-init queue and work on that
597 synchronized (mQueueLock) {
598 queue = new HashSet<String>(mPendingInits);
599 mPendingInits.clear();
600 }
601
602 (new PerformInitializeTask(queue)).run();
603 break;
604 }
605
Christopher Tate2d449afe2010-03-29 19:14:24 -0700606 case MSG_RUN_GET_RESTORE_SETS:
607 {
608 // Like other async operations, this is entered with the wakelock held
609 RestoreSet[] sets = null;
610 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
611 try {
612 sets = params.transport.getAvailableRestoreSets();
613 // cache the result in the active session
614 synchronized (params.session) {
615 params.session.mRestoreSets = sets;
616 }
617 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
618 } catch (Exception e) {
619 Slog.e(TAG, "Error from transport getting set list");
620 } finally {
621 if (params.observer != null) {
622 try {
623 params.observer.restoreSetsAvailable(sets);
624 } catch (RemoteException re) {
625 Slog.e(TAG, "Unable to report listing to observer");
626 } catch (Exception e) {
627 Slog.e(TAG, "Restore observer threw", e);
628 }
629 }
630
Christopher Tate2a935092011-03-03 17:30:32 -0800631 // Done: reset the session timeout clock
632 removeMessages(MSG_RESTORE_TIMEOUT);
633 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
634
Christopher Tate2d449afe2010-03-29 19:14:24 -0700635 mWakelock.release();
636 }
637 break;
638 }
639
Christopher Tate44a27902010-01-27 17:15:49 -0800640 case MSG_TIMEOUT:
641 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700642 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800643 break;
644 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800645
646 case MSG_RESTORE_TIMEOUT:
647 {
648 synchronized (BackupManagerService.this) {
649 if (mActiveRestoreSession != null) {
650 // Client app left the restore session dangling. We know that it
651 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700652 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800653 // up now.
654 Slog.w(TAG, "Restore session timed out; aborting");
655 post(mActiveRestoreSession.new EndRestoreRunnable(
656 BackupManagerService.this, mActiveRestoreSession));
657 }
658 }
659 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700660
661 case MSG_FULL_CONFIRMATION_TIMEOUT:
662 {
663 synchronized (mFullConfirmations) {
664 FullParams params = mFullConfirmations.get(msg.arg1);
665 if (params != null) {
666 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
667
668 // Release the waiter; timeout == completion
669 signalFullBackupRestoreCompletion(params);
670
671 // Remove the token from the set
672 mFullConfirmations.delete(msg.arg1);
673
674 // Report a timeout to the observer, if any
675 if (params.observer != null) {
676 try {
677 params.observer.onTimeout();
678 } catch (RemoteException e) {
679 /* don't care if the app has gone away */
680 }
681 }
682 } else {
683 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
684 }
685 }
686 break;
687 }
Christopher Tate44a27902010-01-27 17:15:49 -0800688 }
689 }
690 }
691
Christopher Tate6de74ff2012-01-17 15:20:32 -0800692 // ----- Debug-only backup operation trace -----
693 void addBackupTrace(String s) {
694 if (DEBUG_BACKUP_TRACE) {
695 synchronized (mBackupTrace) {
696 mBackupTrace.add(s);
697 }
698 }
699 }
700
701 void clearBackupTrace() {
702 if (DEBUG_BACKUP_TRACE) {
703 synchronized (mBackupTrace) {
704 mBackupTrace.clear();
705 }
706 }
707 }
708
Christopher Tate44a27902010-01-27 17:15:49 -0800709 // ----- Main service implementation -----
710
Christopher Tate487529a2009-04-29 14:03:25 -0700711 public BackupManagerService(Context context) {
712 mContext = context;
713 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700714 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700715 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700716
Christopher Tateb6787f22009-07-02 17:40:45 -0700717 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
718 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700719 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700720
Christopher Tate44a27902010-01-27 17:15:49 -0800721 mBackupManagerBinder = asInterface(asBinder());
722
723 // spin up the backup/restore handler thread
724 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
725 mHandlerThread.start();
726 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
727
Christopher Tate22b87872009-05-04 16:41:53 -0700728 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700729 final ContentResolver resolver = context.getContentResolver();
730 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700731 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700732 mProvisioned = Settings.Global.getInt(resolver,
733 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700734 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800735 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700736
737 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
738 resolver.registerContentObserver(
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700739 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
Christopher Tate97ea1222012-05-17 14:59:41 -0700740 false, mProvisionedObserver);
741
Oscar Montemayora8529f62009-11-18 10:14:20 -0800742 // If Encrypted file systems is enabled or disabled, this call will return the
743 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600744 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800745 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700746 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700747
Christopher Tate2efd2db2011-07-19 16:32:49 -0700748 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
749 if (mPasswordHashFile.exists()) {
750 FileInputStream fin = null;
751 DataInputStream in = null;
752 try {
753 fin = new FileInputStream(mPasswordHashFile);
754 in = new DataInputStream(new BufferedInputStream(fin));
755 // integer length of the salt array, followed by the salt,
756 // then the hex pw hash string
757 int saltLen = in.readInt();
758 byte[] salt = new byte[saltLen];
759 in.readFully(salt);
760 mPasswordHash = in.readUTF();
761 mPasswordSalt = salt;
762 } catch (IOException e) {
763 Slog.e(TAG, "Unable to read saved backup pw hash");
764 } finally {
765 try {
766 if (in != null) in.close();
767 if (fin != null) fin.close();
768 } catch (IOException e) {
769 Slog.w(TAG, "Unable to close streams");
770 }
771 }
772 }
773
Christopher Tate4cc86e12009-09-21 19:36:51 -0700774 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700775 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700776 IntentFilter filter = new IntentFilter();
777 filter.addAction(RUN_BACKUP_ACTION);
778 context.registerReceiver(mRunBackupReceiver, filter,
779 android.Manifest.permission.BACKUP, null);
780
781 mRunInitReceiver = new RunInitializeReceiver();
782 filter = new IntentFilter();
783 filter.addAction(RUN_INITIALIZE_ACTION);
784 context.registerReceiver(mRunInitReceiver, filter,
785 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700786
787 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700788 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
789 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
790
Christopher Tate4cc86e12009-09-21 19:36:51 -0700791 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
792 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
793 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
794
Christopher Tatecde87f42009-06-12 12:55:53 -0700795 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700796 mJournalDir = new File(mBaseStateDir, "pending");
797 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700798 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700799
Christopher Tate73e02522009-07-15 14:18:26 -0700800 // Set up the various sorts of package tracking we do
801 initPackageTracking();
802
Christopher Tateabce4e82009-06-18 18:35:32 -0700803 // Build our mapping of uid to backup client services. This implicitly
804 // schedules a backup pass on the Package Manager metadata the first
805 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700806 synchronized (mBackupParticipants) {
807 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700808 }
809
Dan Egnor87a02bc2009-06-17 02:30:10 -0700810 // Set up our transport options and initialize the default transport
811 // TODO: Have transports register themselves somehow?
812 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700813 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700814 ComponentName localName = new ComponentName(context, LocalTransport.class);
815 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700816
Christopher Tate91717492009-06-26 21:07:13 -0700817 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700818 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
819 Settings.Secure.BACKUP_TRANSPORT);
820 if ("".equals(mCurrentTransport)) {
821 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700822 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700824
825 // Attach to the Google backup transport. When this comes up, it will set
826 // itself as the current transport because we explicitly reset mCurrentTransport
827 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700828 ComponentName transportComponent = new ComponentName("com.google.android.backup",
829 "com.google.android.backup.BackupTransportService");
830 try {
831 // If there's something out there that is supposed to be the Google
832 // backup transport, make sure it's legitimately part of the OS build
833 // and not an app lying about its package name.
834 ApplicationInfo info = mPackageManager.getApplicationInfo(
835 transportComponent.getPackageName(), 0);
836 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
837 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
838 Intent intent = new Intent().setComponent(transportComponent);
839 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
840 } else {
841 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
842 }
843 } catch (PackageManager.NameNotFoundException nnf) {
844 // No such package? No binding.
845 if (DEBUG) Slog.v(TAG, "Google transport not present");
846 }
Christopher Tateaa088442009-06-16 18:25:46 -0700847
Christopher Tatecde87f42009-06-12 12:55:53 -0700848 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700849 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700850 parseLeftoverJournals();
851
Christopher Tateb6787f22009-07-02 17:40:45 -0700852 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700853 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700854
855 // Start the backup passes going
856 setBackupEnabled(areEnabled);
857 }
858
859 private class RunBackupReceiver extends BroadcastReceiver {
860 public void onReceive(Context context, Intent intent) {
861 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700862 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700863 if (mPendingInits.size() > 0) {
864 // If there are pending init operations, we process those
865 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700867 try {
868 mAlarmManager.cancel(mRunInitIntent);
869 mRunInitIntent.send();
870 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700872 // can't really do more than bail here
873 }
874 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800875 // Don't run backups now if we're disabled or not yet
876 // fully set up.
877 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700878 if (!mBackupRunning) {
879 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700880
Christopher Tate336a6492011-10-05 16:05:43 -0700881 // Acquire the wakelock and pass it to the backup thread. it will
882 // be released once backup concludes.
883 mBackupRunning = true;
884 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700885
Christopher Tate336a6492011-10-05 16:05:43 -0700886 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
887 mBackupHandler.sendMessage(msg);
888 } else {
889 Slog.i(TAG, "Backup time but one already running");
890 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700891 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800892 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700893 }
894 }
895 }
896 }
897 }
898 }
899
900 private class RunInitializeReceiver extends BroadcastReceiver {
901 public void onReceive(Context context, Intent intent) {
902 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
903 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700905
906 // Acquire the wakelock and pass it to the init thread. it will
907 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700908 mWakelock.acquire();
909
Christopher Tate4cc86e12009-09-21 19:36:51 -0700910 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700911 mBackupHandler.sendMessage(msg);
912 }
913 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700914 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700915 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700916
Christopher Tate73e02522009-07-15 14:18:26 -0700917 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700919
Christopher Tate84725812010-02-04 15:52:40 -0800920 // Remember our ancestral dataset
921 mTokenFile = new File(mBaseStateDir, "ancestral");
922 try {
923 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800924 int version = tf.readInt();
925 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
926 mAncestralToken = tf.readLong();
927 mCurrentToken = tf.readLong();
928
929 int numPackages = tf.readInt();
930 if (numPackages >= 0) {
931 mAncestralPackages = new HashSet<String>();
932 for (int i = 0; i < numPackages; i++) {
933 String pkgName = tf.readUTF();
934 mAncestralPackages.add(pkgName);
935 }
936 }
937 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800938 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800939 } catch (FileNotFoundException fnf) {
940 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800941 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800942 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800943 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800944 }
945
Christopher Tatee97e8072009-07-15 16:45:50 -0700946 // Keep a log of what apps we've ever backed up. Because we might have
947 // rebooted in the middle of an operation that was removing something from
948 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700949 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700950 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700951
Christopher Tatee97e8072009-07-15 16:45:50 -0700952 // If we were in the middle of removing something from the ever-backed-up
953 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700954 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700955 if (tempProcessedFile.exists()) {
956 tempProcessedFile.delete();
957 }
958
Dan Egnor852f8e42009-09-30 11:20:45 -0700959 // If there are previous contents, parse them out then start a new
960 // file to continue the recordkeeping.
961 if (mEverStored.exists()) {
962 RandomAccessFile temp = null;
963 RandomAccessFile in = null;
964
965 try {
966 temp = new RandomAccessFile(tempProcessedFile, "rws");
967 in = new RandomAccessFile(mEverStored, "r");
968
969 while (true) {
970 PackageInfo info;
971 String pkg = in.readUTF();
972 try {
973 info = mPackageManager.getPackageInfo(pkg, 0);
974 mEverStoredApps.add(pkg);
975 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700976 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700977 } catch (NameNotFoundException e) {
978 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700979 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700980 }
981 }
982 } catch (EOFException e) {
983 // Once we've rewritten the backup history log, atomically replace the
984 // old one with the new one then reopen the file for continuing use.
985 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700987 }
988 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700990 } finally {
991 try { if (temp != null) temp.close(); } catch (IOException e) {}
992 try { if (in != null) in.close(); } catch (IOException e) {}
993 }
994 }
995
Christopher Tate73e02522009-07-15 14:18:26 -0700996 // Register for broadcasts about package install, etc., so we can
997 // update the provider list.
998 IntentFilter filter = new IntentFilter();
999 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1000 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1001 filter.addDataScheme("package");
1002 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001003 // Register for events related to sdcard installation.
1004 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001005 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1006 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001007 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001008 }
1009
Christopher Tatecde87f42009-06-12 12:55:53 -07001010 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001011 for (File f : mJournalDir.listFiles()) {
1012 if (mJournal == null || f.compareTo(mJournal) != 0) {
1013 // This isn't the current journal, so it must be a leftover. Read
1014 // out the package names mentioned there and schedule them for
1015 // backup.
1016 RandomAccessFile in = null;
1017 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001018 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001019 in = new RandomAccessFile(f, "r");
1020 while (true) {
1021 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001022 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001023 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001024 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001025 } catch (EOFException e) {
1026 // no more data; we're done
1027 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001029 } finally {
1030 // close/delete the file
1031 try { if (in != null) in.close(); } catch (IOException e) {}
1032 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001033 }
1034 }
1035 }
1036 }
1037
Christopher Tate2efd2db2011-07-19 16:32:49 -07001038 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1039 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1040 }
1041
1042 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1043 try {
1044 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1045 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1046 return keyFactory.generateSecret(ks);
1047 } catch (InvalidKeySpecException e) {
1048 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1049 } catch (NoSuchAlgorithmException e) {
1050 Slog.e(TAG, "PBKDF2 unavailable!");
1051 }
1052 return null;
1053 }
1054
1055 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1056 SecretKey key = buildPasswordKey(pw, salt, rounds);
1057 if (key != null) {
1058 return byteArrayToHex(key.getEncoded());
1059 }
1060 return null;
1061 }
1062
1063 private String byteArrayToHex(byte[] data) {
1064 StringBuilder buf = new StringBuilder(data.length * 2);
1065 for (int i = 0; i < data.length; i++) {
1066 buf.append(Byte.toHexString(data[i], true));
1067 }
1068 return buf.toString();
1069 }
1070
1071 private byte[] hexToByteArray(String digits) {
1072 final int bytes = digits.length() / 2;
1073 if (2*bytes != digits.length()) {
1074 throw new IllegalArgumentException("Hex string must have an even number of digits");
1075 }
1076
1077 byte[] result = new byte[bytes];
1078 for (int i = 0; i < digits.length(); i += 2) {
1079 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1080 }
1081 return result;
1082 }
1083
1084 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1085 char[] mkAsChar = new char[pwBytes.length];
1086 for (int i = 0; i < pwBytes.length; i++) {
1087 mkAsChar[i] = (char) pwBytes[i];
1088 }
1089
1090 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1091 return checksum.getEncoded();
1092 }
1093
1094 // Used for generating random salts or passwords
1095 private byte[] randomBytes(int bits) {
1096 byte[] array = new byte[bits / 8];
1097 mRng.nextBytes(array);
1098 return array;
1099 }
1100
1101 // Backup password management
1102 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001103 // First, on an encrypted device we require matching the device pw
1104 final boolean isEncrypted;
1105 try {
1106 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1107 if (isEncrypted) {
1108 if (DEBUG) {
1109 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1110 }
1111 // 0 means the password validated
1112 // -2 means device not encrypted
1113 // Any other result is either password failure or an error condition,
1114 // so we refuse the match
1115 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1116 if (result == 0) {
1117 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1118 return true;
1119 } else if (result != -2) {
1120 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1121 return false;
1122 } else {
1123 // ...else the device is supposedly not encrypted. HOWEVER, the
1124 // query about the encryption state said that the device *is*
1125 // encrypted, so ... we may have a problem. Log it and refuse
1126 // the backup.
1127 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1128 return false;
1129 }
1130 }
1131 } catch (Exception e) {
1132 // Something went wrong talking to the mount service. This is very bad;
1133 // assume that we fail password validation.
1134 return false;
1135 }
1136
Christopher Tate2efd2db2011-07-19 16:32:49 -07001137 if (mPasswordHash == null) {
1138 // no current password case -- require that 'currentPw' be null or empty
1139 if (candidatePw == null || "".equals(candidatePw)) {
1140 return true;
1141 } // else the non-empty candidate does not match the empty stored pw
1142 } else {
1143 // hash the stated current pw and compare to the stored one
1144 if (candidatePw != null && candidatePw.length() > 0) {
1145 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1146 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1147 // candidate hash matches the stored hash -- the password matches
1148 return true;
1149 }
1150 } // else the stored pw is nonempty but the candidate is empty; no match
1151 }
1152 return false;
1153 }
1154
1155 @Override
1156 public boolean setBackupPassword(String currentPw, String newPw) {
1157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1158 "setBackupPassword");
1159
1160 // If the supplied pw doesn't hash to the the saved one, fail
1161 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1162 return false;
1163 }
1164
1165 // Clearing the password is okay
1166 if (newPw == null || newPw.isEmpty()) {
1167 if (mPasswordHashFile.exists()) {
1168 if (!mPasswordHashFile.delete()) {
1169 // Unable to delete the old pw file, so fail
1170 Slog.e(TAG, "Unable to clear backup password");
1171 return false;
1172 }
1173 }
1174 mPasswordHash = null;
1175 mPasswordSalt = null;
1176 return true;
1177 }
1178
1179 try {
1180 // Okay, build the hash of the new backup password
1181 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1182 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1183
1184 OutputStream pwf = null, buffer = null;
1185 DataOutputStream out = null;
1186 try {
1187 pwf = new FileOutputStream(mPasswordHashFile);
1188 buffer = new BufferedOutputStream(pwf);
1189 out = new DataOutputStream(buffer);
1190 // integer length of the salt array, followed by the salt,
1191 // then the hex pw hash string
1192 out.writeInt(salt.length);
1193 out.write(salt);
1194 out.writeUTF(newPwHash);
1195 out.flush();
1196 mPasswordHash = newPwHash;
1197 mPasswordSalt = salt;
1198 return true;
1199 } finally {
1200 if (out != null) out.close();
1201 if (buffer != null) buffer.close();
1202 if (pwf != null) pwf.close();
1203 }
1204 } catch (IOException e) {
1205 Slog.e(TAG, "Unable to set backup password");
1206 }
1207 return false;
1208 }
1209
1210 @Override
1211 public boolean hasBackupPassword() {
1212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1213 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001214
1215 try {
1216 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1217 || (mPasswordHash != null && mPasswordHash.length() > 0);
1218 } catch (Exception e) {
1219 // If we can't talk to the mount service we have a serious problem; fail
1220 // "secure" i.e. assuming that we require a password
1221 return true;
1222 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001223 }
1224
Christopher Tate4cc86e12009-09-21 19:36:51 -07001225 // Maintain persistent state around whether need to do an initialize operation.
1226 // Must be called with the queue lock held.
1227 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001228 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001229 + " on transport " + transportName);
1230 try {
1231 IBackupTransport transport = getTransport(transportName);
1232 String transportDirName = transport.transportDirName();
1233 File stateDir = new File(mBaseStateDir, transportDirName);
1234 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1235
1236 if (isPending) {
1237 // We need an init before we can proceed with sending backup data.
1238 // Record that with an entry in our set of pending inits, as well as
1239 // journaling it via creation of a sentinel file.
1240 mPendingInits.add(transportName);
1241 try {
1242 (new FileOutputStream(initPendingFile)).close();
1243 } catch (IOException ioe) {
1244 // Something is badly wrong with our permissions; just try to move on
1245 }
1246 } else {
1247 // No more initialization needed; wipe the journal and reset our state.
1248 initPendingFile.delete();
1249 mPendingInits.remove(transportName);
1250 }
1251 } catch (RemoteException e) {
1252 // can't happen; the transport is local
1253 }
1254 }
1255
Christopher Tated55e18a2009-09-21 10:12:59 -07001256 // Reset all of our bookkeeping, in response to having been told that
1257 // the backend data has been wiped [due to idle expiry, for example],
1258 // so we must re-upload all saved settings.
1259 void resetBackupState(File stateFileDir) {
1260 synchronized (mQueueLock) {
1261 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001262 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001263 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001264
Christopher Tate84725812010-02-04 15:52:40 -08001265 mCurrentToken = 0;
1266 writeRestoreTokens();
1267
Christopher Tated55e18a2009-09-21 10:12:59 -07001268 // Remove all the state files
1269 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001270 // ... but don't touch the needs-init sentinel
1271 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1272 sf.delete();
1273 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001274 }
Christopher Tate45597642011-04-04 16:59:21 -07001275 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001276
Christopher Tate45597642011-04-04 16:59:21 -07001277 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001278 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001279 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001280 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001281 HashSet<String> participants = mBackupParticipants.valueAt(i);
1282 if (participants != null) {
1283 for (String packageName : participants) {
1284 dataChangedImpl(packageName);
1285 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001286 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001287 }
1288 }
1289 }
1290
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001291 // Add a transport to our set of available backends. If 'transport' is null, this
1292 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001293 private void registerTransport(String name, IBackupTransport transport) {
1294 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001296 if (transport != null) {
1297 mTransports.put(name, transport);
1298 } else {
1299 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001300 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001301 mCurrentTransport = null;
1302 }
1303 // Nothing further to do in the unregistration case
1304 return;
1305 }
Christopher Tate91717492009-06-26 21:07:13 -07001306 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001307
1308 // If the init sentinel file exists, we need to be sure to perform the init
1309 // as soon as practical. We also create the state directory at registration
1310 // time to ensure it's present from the outset.
1311 try {
1312 String transportName = transport.transportDirName();
1313 File stateDir = new File(mBaseStateDir, transportName);
1314 stateDir.mkdirs();
1315
1316 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1317 if (initSentinel.exists()) {
1318 synchronized (mQueueLock) {
1319 mPendingInits.add(transportName);
1320
1321 // TODO: pick a better starting time than now + 1 minute
1322 long delay = 1000 * 60; // one minute, in milliseconds
1323 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1324 System.currentTimeMillis() + delay, mRunInitIntent);
1325 }
1326 }
1327 } catch (RemoteException e) {
1328 // can't happen, the transport is local
1329 }
Christopher Tate91717492009-06-26 21:07:13 -07001330 }
1331
Christopher Tate3799bc22009-05-06 16:13:56 -07001332 // ----- Track installation/removal of packages -----
1333 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1334 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001335 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001336
Christopher Tate3799bc22009-05-06 16:13:56 -07001337 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001338 boolean replacing = false;
1339 boolean added = false;
1340 Bundle extras = intent.getExtras();
1341 String pkgList[] = null;
1342 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001343 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001344 Uri uri = intent.getData();
1345 if (uri == null) {
1346 return;
1347 }
1348 String pkgName = uri.getSchemeSpecificPart();
1349 if (pkgName != null) {
1350 pkgList = new String[] { pkgName };
1351 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001352 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1353 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001354 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001355 added = true;
1356 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001357 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001358 added = false;
1359 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1360 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001361
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001362 if (pkgList == null || pkgList.length == 0) {
1363 return;
1364 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001365
1366 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001367 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001368 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001369 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001370 // This is the package-replaced case; we just remove the entry
1371 // under the old uid and fall through to re-add.
1372 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001373 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001374 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001376 } else {
1377 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001378 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1379 } else {
1380 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001381 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001382 }
1383 }
1384 }
1385 }
1386 };
1387
Dan Egnor87a02bc2009-06-17 02:30:10 -07001388 // ----- Track connection to GoogleBackupTransport service -----
1389 ServiceConnection mGoogleConnection = new ServiceConnection() {
1390 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001391 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001392 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001393 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001394 }
1395
1396 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001398 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001399 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001400 }
1401 };
1402
Christopher Tate0bacfd22012-01-11 14:41:19 -08001403 // Add the backup agents in the given packages to our set of known backup participants.
1404 // If 'packageNames' is null, adds all backup agents in the whole system.
1405 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001406 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001407 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001408 if (packageNames != null) {
1409 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1410 for (String packageName : packageNames) {
1411 addPackageParticipantsLockedInner(packageName, targetApps);
1412 }
1413 } else {
1414 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1415 addPackageParticipantsLockedInner(null, targetApps);
1416 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001417 }
1418
Christopher Tate181fafa2009-05-14 11:12:14 -07001419 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001420 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001421 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001422 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001423 }
1424
Dan Egnorefe52642009-06-24 00:16:33 -07001425 for (PackageInfo pkg : targetPkgs) {
1426 if (packageName == null || pkg.packageName.equals(packageName)) {
1427 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001428 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001429 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001430 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001431 mBackupParticipants.put(uid, set);
1432 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001433 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001434 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001435
1436 // If we've never seen this app before, schedule a backup for it
1437 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001438 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001439 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001440 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001441 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001442 }
Christopher Tate487529a2009-04-29 14:03:25 -07001443 }
1444 }
1445
Christopher Tate0bacfd22012-01-11 14:41:19 -08001446 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001447 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001448 if (packageNames == null) {
1449 Slog.w(TAG, "removePackageParticipants with null list");
1450 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001451 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001452
Christopher Tatea3d55342012-03-27 13:16:18 -07001453 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1454 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001455 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001456 // Known previous UID, so we know which package set to check
1457 HashSet<String> set = mBackupParticipants.get(oldUid);
1458 if (set != null && set.contains(pkg)) {
1459 removePackageFromSetLocked(set, pkg);
1460 if (set.isEmpty()) {
1461 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1462 mBackupParticipants.remove(oldUid);
1463 }
1464 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001465 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001466 }
1467
Christopher Tatea3d55342012-03-27 13:16:18 -07001468 private void removePackageFromSetLocked(final HashSet<String> set,
1469 final String packageName) {
1470 if (set.contains(packageName)) {
1471 // Found it. Remove this one package from the bookkeeping, and
1472 // if it's the last participating app under this uid we drop the
1473 // (now-empty) set as well.
1474 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
1475 removeEverBackedUp(packageName);
1476 set.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001477 }
1478 }
1479
Christopher Tate181fafa2009-05-14 11:12:14 -07001480 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001481 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001482 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001483 int flags = PackageManager.GET_SIGNATURES;
1484 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1485 int N = packages.size();
1486 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001487 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001488 try {
1489 ApplicationInfo app = pkg.applicationInfo;
1490 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001491 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001492 packages.remove(a);
1493 }
1494 else {
1495 // we will need the shared library path, so look that up and store it here
1496 app = mPackageManager.getApplicationInfo(pkg.packageName,
1497 PackageManager.GET_SHARED_LIBRARY_FILES);
1498 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1499 }
1500 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001501 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001502 }
1503 }
Dan Egnorefe52642009-06-24 00:16:33 -07001504 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001505 }
Christopher Tateaa088442009-06-16 18:25:46 -07001506
Christopher Tate84725812010-02-04 15:52:40 -08001507 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001508 // backed up at least once
1509 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001510 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1511
1512 synchronized (mEverStoredApps) {
1513 if (!mEverStoredApps.add(packageName)) return;
1514
1515 RandomAccessFile out = null;
1516 try {
1517 out = new RandomAccessFile(mEverStored, "rws");
1518 out.seek(out.length());
1519 out.writeUTF(packageName);
1520 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001522 } finally {
1523 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001524 }
1525 }
1526 }
1527
Christopher Tatee97e8072009-07-15 16:45:50 -07001528 // Remove our awareness of having ever backed up the given package
1529 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001530 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1531 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001532
Dan Egnor852f8e42009-09-30 11:20:45 -07001533 synchronized (mEverStoredApps) {
1534 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1535 // we'll recognize on initialization time that the package no longer
1536 // exists and fix it up then.
1537 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1538 RandomAccessFile known = null;
1539 try {
1540 known = new RandomAccessFile(tempKnownFile, "rws");
1541 mEverStoredApps.remove(packageName);
1542 for (String s : mEverStoredApps) {
1543 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001544 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001545 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001546 known.close();
1547 known = null;
1548 if (!tempKnownFile.renameTo(mEverStored)) {
1549 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1550 }
1551 } catch (IOException e) {
1552 // Bad: we couldn't create the new copy. For safety's sake we
1553 // abandon the whole process and remove all what's-backed-up
1554 // state entirely, meaning we'll force a backup pass for every
1555 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001557 mEverStoredApps.clear();
1558 tempKnownFile.delete();
1559 mEverStored.delete();
1560 } finally {
1561 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001562 }
1563 }
1564 }
1565
Christopher Tateb49ceb32010-02-08 16:22:24 -08001566 // Persistently record the current and ancestral backup tokens as well
1567 // as the set of packages with data [supposedly] available in the
1568 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001569 void writeRestoreTokens() {
1570 try {
1571 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001572
1573 // First, the version number of this record, for futureproofing
1574 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1575
1576 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001577 af.writeLong(mAncestralToken);
1578 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001579
1580 // Now write the set of ancestral packages
1581 if (mAncestralPackages == null) {
1582 af.writeInt(-1);
1583 } else {
1584 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001586 for (String pkgName : mAncestralPackages) {
1587 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001588 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001589 }
1590 }
Christopher Tate84725812010-02-04 15:52:40 -08001591 af.close();
1592 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001593 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001594 }
1595 }
1596
Dan Egnor87a02bc2009-06-17 02:30:10 -07001597 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001598 private IBackupTransport getTransport(String transportName) {
1599 synchronized (mTransports) {
1600 IBackupTransport transport = mTransports.get(transportName);
1601 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001602 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001603 }
1604 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001605 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001606 }
1607
Christopher Tatedf01dea2009-06-09 20:45:02 -07001608 // fire off a backup agent, blocking until it attaches or times out
1609 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1610 IBackupAgent agent = null;
1611 synchronized(mAgentConnectLock) {
1612 mConnecting = true;
1613 mConnectedAgent = null;
1614 try {
1615 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001617
1618 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001619 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001620 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1621 while (mConnecting && mConnectedAgent == null
1622 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001623 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001624 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001625 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001626 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001627 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628 return null;
1629 }
1630 }
1631
1632 // if we timed out with no connect, abort and move on
1633 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001635 return null;
1636 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001637 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 agent = mConnectedAgent;
1639 }
1640 } catch (RemoteException e) {
1641 // can't happen
1642 }
1643 }
1644 return agent;
1645 }
1646
Christopher Tatec7b31e32009-06-10 15:49:30 -07001647 // clear an application's data, blocking until the operation completes or times out
1648 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001649 // Don't wipe packages marked allowClearUserData=false
1650 try {
1651 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1652 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001653 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001654 + packageName);
1655 return;
1656 }
1657 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001658 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001659 return;
1660 }
1661
Christopher Tatec7b31e32009-06-10 15:49:30 -07001662 ClearDataObserver observer = new ClearDataObserver();
1663
1664 synchronized(mClearDataLock) {
1665 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001666 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001667 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001668 } catch (RemoteException e) {
1669 // can't happen because the activity manager is in this process
1670 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001671
1672 // only wait 10 seconds for the clear data to happen
1673 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1674 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1675 try {
1676 mClearDataLock.wait(5000);
1677 } catch (InterruptedException e) {
1678 // won't happen, but still.
1679 mClearingData = false;
1680 }
1681 }
1682 }
1683 }
1684
1685 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001686 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001687 synchronized(mClearDataLock) {
1688 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001689 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001690 }
1691 }
1692 }
1693
Christopher Tate1bb69062010-02-19 17:02:12 -08001694 // Get the restore-set token for the best-available restore set for this package:
1695 // the active set if possible, else the ancestral one. Returns zero if none available.
1696 long getAvailableRestoreToken(String packageName) {
1697 long token = mAncestralToken;
1698 synchronized (mQueueLock) {
1699 if (mEverStoredApps.contains(packageName)) {
1700 token = mCurrentToken;
1701 }
1702 }
1703 return token;
1704 }
1705
Christopher Tate44a27902010-01-27 17:15:49 -08001706 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001707 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1708
1709 interface BackupRestoreTask {
1710 // Execute one tick of whatever state machine the task implements
1711 void execute();
1712
1713 // An operation that wanted a callback has completed
1714 void operationComplete();
1715
1716 // An operation that wanted a callback has timed out
1717 void handleTimeout();
1718 }
1719
1720 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1721 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1722 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001723 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001724 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1725
1726 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1727 mBackupHandler.sendMessageDelayed(msg, interval);
1728 }
1729 }
1730
1731 // synchronous waiter case
1732 boolean waitUntilOperationComplete(int token) {
1733 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1734 + Integer.toHexString(token));
1735 int finalState = OP_PENDING;
1736 Operation op = null;
1737 synchronized (mCurrentOpLock) {
1738 while (true) {
1739 op = mCurrentOperations.get(token);
1740 if (op == null) {
1741 // mysterious disappearance: treat as success with no callback
1742 break;
1743 } else {
1744 if (op.state == OP_PENDING) {
1745 try {
1746 mCurrentOpLock.wait();
1747 } catch (InterruptedException e) {}
1748 // When the wait is notified we loop around and recheck the current state
1749 } else {
1750 // No longer pending; we're done
1751 finalState = op.state;
1752 break;
1753 }
Christopher Tate44a27902010-01-27 17:15:49 -08001754 }
Christopher Tate44a27902010-01-27 17:15:49 -08001755 }
1756 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001757
Christopher Tate44a27902010-01-27 17:15:49 -08001758 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001759 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001760 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001761 return finalState == OP_ACKNOWLEDGED;
1762 }
1763
Christopher Tate8e294d42011-08-31 20:37:12 -07001764 void handleTimeout(int token, Object obj) {
1765 // Notify any synchronous waiters
1766 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001767 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001768 op = mCurrentOperations.get(token);
1769 if (MORE_DEBUG) {
1770 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1771 + " but no op found");
1772 }
1773 int state = (op != null) ? op.state : OP_TIMEOUT;
1774 if (state == OP_PENDING) {
1775 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1776 op.state = OP_TIMEOUT;
1777 mCurrentOperations.put(token, op);
1778 }
1779 mCurrentOpLock.notifyAll();
1780 }
1781
1782 // If there's a TimeoutHandler for this event, call it
1783 if (op != null && op.callback != null) {
1784 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001785 }
Christopher Tate44a27902010-01-27 17:15:49 -08001786 }
1787
Christopher Tate043dadc2009-06-02 16:11:00 -07001788 // ----- Back up a set of applications via a worker thread -----
1789
Christopher Tate8e294d42011-08-31 20:37:12 -07001790 enum BackupState {
1791 INITIAL,
1792 RUNNING_QUEUE,
1793 FINAL
1794 }
1795
1796 class PerformBackupTask implements BackupRestoreTask {
1797 private static final String TAG = "PerformBackupTask";
1798
Christopher Tateaa088442009-06-16 18:25:46 -07001799 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001800 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001801 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001802 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001803 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001804 BackupState mCurrentState;
1805
1806 // carried information about the current in-flight operation
1807 PackageInfo mCurrentPackage;
1808 File mSavedStateName;
1809 File mBackupDataName;
1810 File mNewStateName;
1811 ParcelFileDescriptor mSavedState;
1812 ParcelFileDescriptor mBackupData;
1813 ParcelFileDescriptor mNewState;
1814 int mStatus;
1815 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001816
Christopher Tate44a27902010-01-27 17:15:49 -08001817 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001818 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001819 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001820 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001821 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001822
1823 try {
1824 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1825 } catch (RemoteException e) {
1826 // can't happen; the transport is local
1827 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001828
1829 mCurrentState = BackupState.INITIAL;
1830 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001831
1832 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001833 }
1834
Christopher Tate8e294d42011-08-31 20:37:12 -07001835 // Main entry point: perform one chunk of work, updating the state as appropriate
1836 // and reposting the next chunk to the primary backup handler thread.
1837 @Override
1838 public void execute() {
1839 switch (mCurrentState) {
1840 case INITIAL:
1841 beginBackup();
1842 break;
1843
1844 case RUNNING_QUEUE:
1845 invokeNextAgent();
1846 break;
1847
1848 case FINAL:
1849 if (!mFinished) finalizeBackup();
1850 else {
1851 Slog.e(TAG, "Duplicate finish");
1852 }
Christopher Tate2982d062011-09-06 20:35:24 -07001853 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001854 break;
1855 }
1856 }
1857
1858 // We're starting a backup pass. Initialize the transport and send
1859 // the PM metadata blob if we haven't already.
1860 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001861 if (DEBUG_BACKUP_TRACE) {
1862 clearBackupTrace();
1863 StringBuilder b = new StringBuilder(256);
1864 b.append("beginBackup: [");
1865 for (BackupRequest req : mOriginalQueue) {
1866 b.append(' ');
1867 b.append(req.packageName);
1868 }
1869 b.append(" ]");
1870 addBackupTrace(b.toString());
1871 }
1872
Christopher Tate8e294d42011-08-31 20:37:12 -07001873 mStatus = BackupConstants.TRANSPORT_OK;
1874
1875 // Sanity check: if the queue is empty we have no work to do.
1876 if (mOriginalQueue.isEmpty()) {
1877 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001878 addBackupTrace("queue empty at begin");
1879 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001880 return;
1881 }
1882
1883 // We need to retain the original queue contents in case of transport
1884 // failure, but we want a working copy that we can manipulate along
1885 // the way.
1886 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1887
Joe Onorato8a9b2202010-02-26 18:56:32 -08001888 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001889
Christopher Tate8e294d42011-08-31 20:37:12 -07001890 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001891 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001892 final String transportName = mTransport.transportDirName();
1893 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001894
Dan Egnor852f8e42009-09-30 11:20:45 -07001895 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001896 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001897 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001898 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001899 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001900 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001901
1902 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001904 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001905 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001907 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001908 }
Dan Egnor01445162009-09-21 17:04:05 -07001909 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001910
1911 // The package manager doesn't have a proper <application> etc, but since
1912 // it's running here in the system process we can just set up its agent
1913 // directly and use a synthetic BackupRequest. We always run this pass
1914 // because it's cheap and this way we guarantee that we don't get out of
1915 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001916 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001917 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1918 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001919 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001920 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001921 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001922 }
Christopher Tate90967f42009-09-20 15:28:33 -07001923
Christopher Tate8e294d42011-08-31 20:37:12 -07001924 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1925 // The backend reports that our dataset has been wiped. Note this in
1926 // the event log; the no-success code below will reset the backup
1927 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001928 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001929 }
1930 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001931 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001932 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001933 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001934 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001935 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1936 // metadata and its completion/timeout callback will continue the state
1937 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001938 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001939 if (mStatus != BackupConstants.TRANSPORT_OK) {
1940 // if things went wrong at this point, we need to
1941 // restage everything and try again later.
1942 resetBackupState(mStateDir); // Just to make sure.
1943 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001944 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001945 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001946 }
1947
Christopher Tate8e294d42011-08-31 20:37:12 -07001948 // Transport has been initialized and the PM metadata submitted successfully
1949 // if that was warranted. Now we process the single next thing in the queue.
1950 void invokeNextAgent() {
1951 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001952 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001953
Christopher Tate8e294d42011-08-31 20:37:12 -07001954 // Sanity check that we have work to do. If not, skip to the end where
1955 // we reestablish the wakelock invariants etc.
1956 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001957 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001958 executeNextState(BackupState.FINAL);
1959 return;
1960 }
1961
1962 // pop the entry we're going to process on this step
1963 BackupRequest request = mQueue.get(0);
1964 mQueue.remove(0);
1965
1966 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001967 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001968
1969 // Verify that the requested app exists; it might be something that
1970 // requested a backup but was then uninstalled. The request was
1971 // journalled and rather than tamper with the journal it's safer
1972 // to sanity-check here. This also gives us the classname of the
1973 // package's backup agent.
1974 try {
1975 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1976 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001977 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1978 // The manifest has changed but we had a stale backup request pending.
1979 // This won't happen again because the app won't be requesting further
1980 // backups.
1981 Slog.i(TAG, "Package " + request.packageName
1982 + " no longer supports backup; skipping");
1983 addBackupTrace("skipping - no agent, completion is noop");
1984 executeNextState(BackupState.RUNNING_QUEUE);
1985 return;
1986 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001987
Christopher Tate043dadc2009-06-02 16:11:00 -07001988 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001989 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001990 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1991 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001992 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001993 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001994 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001995 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1996 // at this point we'll either get a completion callback from the
1997 // agent, or a timeout message on the main handler. either way, we're
1998 // done here as long as we're successful so far.
1999 } else {
2000 // Timeout waiting for the agent
2001 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002002 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002003 } catch (SecurityException ex) {
2004 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002005 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002006 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002007 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002008 }
2009 } catch (NameNotFoundException e) {
2010 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002011 addBackupTrace("no such package");
2012 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002013 } finally {
2014 mWakelock.setWorkSource(null);
2015
2016 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002017 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002018 if (mStatus != BackupConstants.TRANSPORT_OK) {
2019 BackupState nextState = BackupState.RUNNING_QUEUE;
2020
2021 // An agent-level failure means we reenqueue this one agent for
2022 // a later retry, but otherwise proceed normally.
2023 if (mStatus == BackupConstants.AGENT_ERROR) {
2024 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2025 + " - restaging");
2026 dataChangedImpl(request.packageName);
2027 mStatus = BackupConstants.TRANSPORT_OK;
2028 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002029 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2030 // Failed lookup of the app, so we couldn't bring up an agent, but
2031 // we're otherwise fine. Just drop it and go on to the next as usual.
2032 mStatus = BackupConstants.TRANSPORT_OK;
2033 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 // Transport-level failure means we reenqueue everything
2035 revertAndEndBackup();
2036 nextState = BackupState.FINAL;
2037 }
2038
2039 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002040 } else {
2041 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002042 }
2043 }
2044 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002045
Christopher Tate8e294d42011-08-31 20:37:12 -07002046 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002047 addBackupTrace("finishing");
2048
Christopher Tate8e294d42011-08-31 20:37:12 -07002049 // Either backup was successful, in which case we of course do not need
2050 // this pass's journal any more; or it failed, in which case we just
2051 // re-enqueued all of these packages in the current active journal.
2052 // Either way, we no longer need this pass's journal.
2053 if (mJournal != null && !mJournal.delete()) {
2054 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2055 }
2056
2057 // If everything actually went through and this is the first time we've
2058 // done a backup, we can now record what the current backup dataset token
2059 // is.
2060 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002061 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002062 try {
2063 mCurrentToken = mTransport.getCurrentRestoreSet();
2064 } catch (RemoteException e) {} // can't happen
2065 writeRestoreTokens();
2066 }
2067
Christopher Tate336a6492011-10-05 16:05:43 -07002068 // Set up the next backup pass - at this point we can set mBackupRunning
2069 // to false to allow another pass to fire, because we're done with the
2070 // state machine sequence and the wakelock is refcounted.
2071 synchronized (mQueueLock) {
2072 mBackupRunning = false;
2073 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002074 // Make sure we back up everything and perform the one-time init
2075 clearMetadata();
2076 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002077 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002078 backupNow();
2079 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002080 }
2081
2082 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002083 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002084 Slog.i(TAG, "Backup pass finished.");
2085 mWakelock.release();
2086 }
2087
Christopher Tatee659fb92011-10-10 16:34:50 -07002088 // Remove the PM metadata state. This will generate an init on the next pass.
2089 void clearMetadata() {
2090 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2091 if (pmState.exists()) pmState.delete();
2092 }
2093
Christopher Tate8e294d42011-08-31 20:37:12 -07002094 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2095 // handler in case it doesn't get back to us.
2096 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002097 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002098 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2099 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002100
Christopher Tate8e294d42011-08-31 20:37:12 -07002101 mSavedStateName = new File(mStateDir, packageName);
2102 mBackupDataName = new File(mDataDir, packageName + ".data");
2103 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002104
Christopher Tate8e294d42011-08-31 20:37:12 -07002105 mSavedState = null;
2106 mBackupData = null;
2107 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002108
Christopher Tate4a627c72011-04-01 14:43:32 -07002109 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002110 try {
2111 // Look up the package info & signatures. This is first so that if it
2112 // throws an exception, there's no file setup yet that would need to
2113 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002114 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002115 // The metadata 'package' is synthetic; construct one and make
2116 // sure our global state is pointed at it
2117 mCurrentPackage = new PackageInfo();
2118 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002119 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002120
Christopher Tatec7b31e32009-06-10 15:49:30 -07002121 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002122 // the saved-state "file". This is by definition an incremental,
2123 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002124 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002125 ParcelFileDescriptor.MODE_READ_ONLY |
2126 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127
Christopher Tate8e294d42011-08-31 20:37:12 -07002128 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002129 ParcelFileDescriptor.MODE_READ_WRITE |
2130 ParcelFileDescriptor.MODE_CREATE |
2131 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002132
Christopher Tate8e294d42011-08-31 20:37:12 -07002133 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002134 ParcelFileDescriptor.MODE_READ_WRITE |
2135 ParcelFileDescriptor.MODE_CREATE |
2136 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002137
Christopher Tate44a27902010-01-27 17:15:49 -08002138 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002139 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002140 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002141 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002142 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002143 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002145 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002146 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2147 e.toString());
2148 agentErrorCleanup();
2149 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002150 }
2151
Christopher Tate8e294d42011-08-31 20:37:12 -07002152 // At this point the agent is off and running. The next thing to happen will
2153 // either be a callback from the agent, at which point we'll process its data
2154 // for transport, or a timeout. Either way the next phase will happen in
2155 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002156 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002157 return BackupConstants.TRANSPORT_OK;
2158 }
2159
2160 @Override
2161 public void operationComplete() {
2162 // Okay, the agent successfully reported back to us. Spin the data off to the
2163 // transport and proceed with the next stage.
2164 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2165 + mCurrentPackage.packageName);
2166 mBackupHandler.removeMessages(MSG_TIMEOUT);
2167 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002168 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002169
2170 ParcelFileDescriptor backupData = null;
2171 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002172 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002173 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002174 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002175 if (mStatus == BackupConstants.TRANSPORT_OK) {
2176 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002177 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002178 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002179 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002180 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002181
Dan Egnor83861e72009-09-17 16:17:55 -07002182 // TODO - We call finishBackup() for each application backed up, because
2183 // we need to know now whether it succeeded or failed. Instead, we should
2184 // hold off on finishBackup() until the end, which implies holding off on
2185 // renaming *all* the output state files (see below) until that happens.
2186
Christopher Tate6de74ff2012-01-17 15:20:32 -08002187 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002188 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002191 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002192 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002193 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002195 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002196 }
2197
2198 // After successful transport, delete the now-stale data
2199 // and juggle the files so that next time we supply the agent
2200 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002201 if (mStatus == BackupConstants.TRANSPORT_OK) {
2202 mBackupDataName.delete();
2203 mNewStateName.renameTo(mSavedStateName);
2204 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2205 mCurrentPackage.packageName, size);
2206 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002207 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002208 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2209 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002210 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002211 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002212 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2213 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2214 mCurrentPackage.packageName);
2215 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002216 } finally {
2217 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002218 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002219
Christopher Tate8e294d42011-08-31 20:37:12 -07002220 // If we encountered an error here it's a transport-level failure. That
2221 // means we need to halt everything and reschedule everything for next time.
2222 final BackupState nextState;
2223 if (mStatus != BackupConstants.TRANSPORT_OK) {
2224 revertAndEndBackup();
2225 nextState = BackupState.FINAL;
2226 } else {
2227 // Success! Proceed with the next app if any, otherwise we're done.
2228 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2229 }
2230
2231 executeNextState(nextState);
2232 }
2233
2234 @Override
2235 public void handleTimeout() {
2236 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2237 // it for the next time we run a backup pass.
2238 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2239 // fail repeatedly (i.e. have proved themselves to be buggy).
2240 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2241 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2242 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002243 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002244 agentErrorCleanup();
2245 dataChangedImpl(mCurrentPackage.packageName);
2246 }
2247
2248 void revertAndEndBackup() {
2249 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002250 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002251 for (BackupRequest request : mOriginalQueue) {
2252 dataChangedImpl(request.packageName);
2253 }
2254 // We also want to reset the backup schedule based on whatever
2255 // the transport suggests by way of retry/backoff time.
2256 restartBackupAlarm();
2257 }
2258
2259 void agentErrorCleanup() {
2260 mBackupDataName.delete();
2261 mNewStateName.delete();
2262 clearAgentState();
2263
2264 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2265 }
2266
2267 // Cleanup common to both success and failure cases
2268 void clearAgentState() {
2269 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2270 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2271 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2272 mSavedState = mBackupData = mNewState = null;
2273 synchronized (mCurrentOpLock) {
2274 mCurrentOperations.clear();
2275 }
2276
2277 // If this was a pseudopackage there's no associated Activity Manager state
2278 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002279 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002280 try { // unbind even on timeout, just in case
2281 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2282 } catch (RemoteException e) {}
2283 }
2284 }
2285
2286 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002287 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002288 synchronized (mQueueLock) {
2289 try {
2290 startBackupAlarmsLocked(mTransport.requestBackupTime());
2291 } catch (RemoteException e) { /* cannot happen */ }
2292 }
2293 }
2294
2295 void executeNextState(BackupState nextState) {
2296 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2297 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002298 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002299 mCurrentState = nextState;
2300 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2301 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002302 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002303 }
2304
Christopher Tatedf01dea2009-06-09 20:45:02 -07002305
Christopher Tate4a627c72011-04-01 14:43:32 -07002306 // ----- Full backup to a file/socket -----
2307
2308 class PerformFullBackupTask implements Runnable {
2309 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002310 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002311 IFullBackupRestoreObserver mObserver;
2312 boolean mIncludeApks;
2313 boolean mIncludeShared;
2314 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002315 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002316 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002317 String mCurrentPassword;
2318 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002319 AtomicBoolean mLatchObject;
2320 File mFilesDir;
2321 File mManifestFile;
2322
Christopher Tate7926a692011-07-11 11:31:57 -07002323 class FullBackupRunner implements Runnable {
2324 PackageInfo mPackage;
2325 IBackupAgent mAgent;
2326 ParcelFileDescriptor mPipe;
2327 int mToken;
2328 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002329 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002330
2331 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002332 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002333 mPackage = pack;
2334 mAgent = agent;
2335 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2336 mToken = token;
2337 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002338 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002339 }
2340
2341 @Override
2342 public void run() {
2343 try {
2344 BackupDataOutput output = new BackupDataOutput(
2345 mPipe.getFileDescriptor());
2346
Christopher Tate73d73692012-01-20 17:11:31 -08002347 if (mWriteManifest) {
2348 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2349 writeAppManifest(mPackage, mManifestFile, mSendApk);
2350 FullBackup.backupToTar(mPackage.packageName, null, null,
2351 mFilesDir.getAbsolutePath(),
2352 mManifestFile.getAbsolutePath(),
2353 output);
2354 }
Christopher Tate7926a692011-07-11 11:31:57 -07002355
2356 if (mSendApk) {
2357 writeApkToBackup(mPackage, output);
2358 }
2359
Christopher Tatec58efa62011-08-01 19:20:14 -07002360 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002361 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002362 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2363 } catch (IOException e) {
2364 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2365 } catch (RemoteException e) {
2366 Slog.e(TAG, "Remote agent vanished during full backup of "
2367 + mPackage.packageName);
2368 } finally {
2369 try {
2370 mPipe.close();
2371 } catch (IOException e) {}
2372 }
2373 }
2374 }
2375
Christopher Tate4a627c72011-04-01 14:43:32 -07002376 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002377 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002378 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002379 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002380 mOutputFile = fd;
2381 mObserver = observer;
2382 mIncludeApks = includeApks;
2383 mIncludeShared = includeShared;
2384 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002385 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002386 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002387 mCurrentPassword = curPassword;
2388 // when backing up, if there is a current backup password, we require that
2389 // the user use a nonempty encryption password as well. if one is supplied
2390 // in the UI we use that, but if the UI was left empty we fall back to the
2391 // current backup password (which was supplied by the user as well).
2392 if (encryptPassword == null || "".equals(encryptPassword)) {
2393 mEncryptPassword = curPassword;
2394 } else {
2395 mEncryptPassword = encryptPassword;
2396 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002397 mLatchObject = latch;
2398
2399 mFilesDir = new File("/data/system");
2400 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2401 }
2402
2403 @Override
2404 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002405 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002406
Christopher Tateb0628bf2011-06-02 15:08:13 -07002407 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002408 sendStartBackup();
2409
2410 // doAllApps supersedes the package set if any
2411 if (mAllApps) {
2412 packagesToBackup = mPackageManager.getInstalledPackages(
2413 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002414 // Exclude system apps if we've been asked to do so
2415 if (mIncludeSystem == false) {
2416 for (int i = 0; i < packagesToBackup.size(); ) {
2417 PackageInfo pkg = packagesToBackup.get(i);
2418 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2419 packagesToBackup.remove(i);
2420 } else {
2421 i++;
2422 }
2423 }
2424 }
2425 }
2426
2427 // Now process the command line argument packages, if any. Note that explicitly-
2428 // named system-partition packages will be included even if includeSystem was
2429 // set to false.
2430 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002431 for (String pkgName : mPackages) {
2432 try {
2433 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2434 PackageManager.GET_SIGNATURES));
2435 } catch (NameNotFoundException e) {
2436 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2437 }
2438 }
2439 }
2440
Christopher Tate73d73692012-01-20 17:11:31 -08002441 // Cull any packages that have indicated that backups are not permitted, as well
2442 // as any explicit mention of the 'special' shared-storage agent package (we
2443 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002444 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002445 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002446 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2447 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002448 packagesToBackup.remove(i);
2449 } else {
2450 i++;
2451 }
2452 }
2453
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002454 // Cull any packages that run as system-domain uids but do not define their
2455 // own backup agents
2456 for (int i = 0; i < packagesToBackup.size(); ) {
2457 PackageInfo pkg = packagesToBackup.get(i);
2458 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2459 && (pkg.applicationInfo.backupAgentName == null)) {
2460 if (MORE_DEBUG) {
2461 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2462 }
2463 packagesToBackup.remove(i);
2464 } else {
2465 i++;
2466 }
2467 }
2468
Christopher Tate7926a692011-07-11 11:31:57 -07002469 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002470 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002471
Christopher Tate4a627c72011-04-01 14:43:32 -07002472 PackageInfo pkg = null;
2473 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002474 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002475 boolean compressing = COMPRESS_FULL_BACKUPS;
2476 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002477
Christopher Tateeef4ae42011-08-05 13:15:53 -07002478 // Verify that the given password matches the currently-active
2479 // backup password, if any
2480 if (hasBackupPassword()) {
2481 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2482 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2483 return;
2484 }
2485 }
2486
Christopher Tate7bdb0962011-07-13 19:30:21 -07002487 // Write the global file header. All strings are UTF-8 encoded; lines end
2488 // with a '\n' byte. Actual backup data begins immediately following the
2489 // final '\n'.
2490 //
2491 // line 1: "ANDROID BACKUP"
2492 // line 2: backup file format version, currently "1"
2493 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002494 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2495 //
2496 // When line 4 is not "none", then additional header data follows:
2497 //
2498 // line 5: user password salt [hex]
2499 // line 6: master key checksum salt [hex]
2500 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2501 // line 8: IV of the user key [hex]
2502 // line 9: master key blob [hex]
2503 // IV of the master key, master key itself, master key checksum hash
2504 //
2505 // The master key checksum is the master key plus its checksum salt, run through
2506 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2507 // correct password for decrypting the archive: the master key decrypted from
2508 // the archive using the user-supplied password is also run through PBKDF2 in
2509 // this way, and if the result does not match the checksum as stored in the
2510 // archive, then we know that the user-supplied password does not match the
2511 // archive's.
2512 StringBuilder headerbuf = new StringBuilder(1024);
2513
Christopher Tate7bdb0962011-07-13 19:30:21 -07002514 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002515 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2516 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002517
2518 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002519 // Set up the encryption stage if appropriate, and emit the correct header
2520 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002521 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2522 } else {
2523 headerbuf.append("none\n");
2524 }
2525
Christopher Tate7bdb0962011-07-13 19:30:21 -07002526 byte[] header = headerbuf.toString().getBytes("UTF-8");
2527 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002528
2529 // Set up the compression stage feeding into the encryption stage (if any)
2530 if (compressing) {
2531 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2532 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2533 }
2534
2535 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002536 } catch (Exception e) {
2537 // Should never happen!
2538 Slog.e(TAG, "Unable to emit archive header", e);
2539 return;
2540 }
2541
Christopher Tate73d73692012-01-20 17:11:31 -08002542 // Shared storage if requested
2543 if (mIncludeShared) {
2544 try {
2545 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2546 packagesToBackup.add(pkg);
2547 } catch (NameNotFoundException e) {
2548 Slog.e(TAG, "Unable to find shared-storage backup handler");
2549 }
2550 }
2551
Christopher Tateb0628bf2011-06-02 15:08:13 -07002552 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002553 int N = packagesToBackup.size();
2554 for (int i = 0; i < N; i++) {
2555 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002556 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002557 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002558
Christopher Tate6853fcf2011-08-10 17:52:21 -07002559 // Done!
2560 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002561 } catch (RemoteException e) {
2562 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002563 } catch (Exception e) {
2564 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002565 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002566 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002567 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002568 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002569 mOutputFile.close();
2570 } catch (IOException e) {
2571 /* nothing we can do about this */
2572 }
2573 synchronized (mCurrentOpLock) {
2574 mCurrentOperations.clear();
2575 }
2576 synchronized (mLatchObject) {
2577 mLatchObject.set(true);
2578 mLatchObject.notifyAll();
2579 }
2580 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002581 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002582 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002583 }
2584 }
2585
Christopher Tate2efd2db2011-07-19 16:32:49 -07002586 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2587 OutputStream ofstream) throws Exception {
2588 // User key will be used to encrypt the master key.
2589 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002590 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002591 PBKDF2_HASH_ROUNDS);
2592
2593 // the master key is random for each backup
2594 byte[] masterPw = new byte[256 / 8];
2595 mRng.nextBytes(masterPw);
2596 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2597
2598 // primary encryption of the datastream with the random key
2599 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2600 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2601 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2602 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2603
2604 // line 4: name of encryption algorithm
2605 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2606 headerbuf.append('\n');
2607 // line 5: user password salt [hex]
2608 headerbuf.append(byteArrayToHex(newUserSalt));
2609 headerbuf.append('\n');
2610 // line 6: master key checksum salt [hex]
2611 headerbuf.append(byteArrayToHex(checksumSalt));
2612 headerbuf.append('\n');
2613 // line 7: number of PBKDF2 rounds used [decimal]
2614 headerbuf.append(PBKDF2_HASH_ROUNDS);
2615 headerbuf.append('\n');
2616
2617 // line 8: IV of the user key [hex]
2618 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2619 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2620
2621 byte[] IV = mkC.getIV();
2622 headerbuf.append(byteArrayToHex(IV));
2623 headerbuf.append('\n');
2624
2625 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2626 // [byte] IV length = Niv
2627 // [array of Niv bytes] IV itself
2628 // [byte] master key length = Nmk
2629 // [array of Nmk bytes] master key itself
2630 // [byte] MK checksum hash length = Nck
2631 // [array of Nck bytes] master key checksum hash
2632 //
2633 // The checksum is the (master key + checksum salt), run through the
2634 // stated number of PBKDF2 rounds
2635 IV = c.getIV();
2636 byte[] mk = masterKeySpec.getEncoded();
2637 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2638 checksumSalt, PBKDF2_HASH_ROUNDS);
2639
2640 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2641 + checksum.length + 3);
2642 DataOutputStream mkOut = new DataOutputStream(blob);
2643 mkOut.writeByte(IV.length);
2644 mkOut.write(IV);
2645 mkOut.writeByte(mk.length);
2646 mkOut.write(mk);
2647 mkOut.writeByte(checksum.length);
2648 mkOut.write(checksum);
2649 mkOut.flush();
2650 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2651 headerbuf.append(byteArrayToHex(encryptedMk));
2652 headerbuf.append('\n');
2653
2654 return finalOutput;
2655 }
2656
2657 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002658 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002659 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2660
2661 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2662 IApplicationThread.BACKUP_MODE_FULL);
2663 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002664 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002665 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002666 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002667
Christopher Tateb0628bf2011-06-02 15:08:13 -07002668 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002669 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002670 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002671 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002672 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2673 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2674 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2675
Christopher Tate73d73692012-01-20 17:11:31 -08002676 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002677
Christopher Tate7926a692011-07-11 11:31:57 -07002678 final int token = generateToken();
2679 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002680 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002681 pipes[1].close(); // the runner has dup'd it
2682 pipes[1] = null;
2683 Thread t = new Thread(runner);
2684 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002685
Christopher Tate7926a692011-07-11 11:31:57 -07002686 // Now pull data from the app and stuff it into the compressor
2687 try {
2688 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2689 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002690
Christopher Tate7926a692011-07-11 11:31:57 -07002691 byte[] buffer = new byte[16 * 1024];
2692 int chunkTotal;
2693 while ((chunkTotal = in.readInt()) > 0) {
2694 while (chunkTotal > 0) {
2695 int toRead = (chunkTotal > buffer.length)
2696 ? buffer.length : chunkTotal;
2697 int nRead = in.read(buffer, 0, toRead);
2698 out.write(buffer, 0, nRead);
2699 chunkTotal -= nRead;
2700 }
2701 }
2702 } catch (IOException e) {
2703 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002704 }
2705
Christopher Tateb0628bf2011-06-02 15:08:13 -07002706 if (!waitUntilOperationComplete(token)) {
2707 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2708 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002709 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002710 }
Christopher Tate7926a692011-07-11 11:31:57 -07002711
Christopher Tateb0628bf2011-06-02 15:08:13 -07002712 } catch (IOException e) {
2713 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002714 } finally {
2715 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002716 // flush after every package
2717 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002718 if (pipes != null) {
2719 if (pipes[0] != null) pipes[0].close();
2720 if (pipes[1] != null) pipes[1].close();
2721 }
Christopher Tate7926a692011-07-11 11:31:57 -07002722 } catch (IOException e) {
2723 Slog.w(TAG, "Error bringing down backup stack");
2724 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002725 }
2726 } else {
2727 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2728 }
2729 tearDown(pkg);
2730 }
2731
Christopher Tate79ec80d2011-06-24 14:58:49 -07002732 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2733 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2734 final String appSourceDir = pkg.applicationInfo.sourceDir;
2735 final String apkDir = new File(appSourceDir).getParent();
2736 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2737 apkDir, appSourceDir, output);
2738
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002739 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2740 // doesn't have access to external storage.
2741
Christopher Tate79ec80d2011-06-24 14:58:49 -07002742 // Save associated .obb content if it exists and we did save the apk
2743 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002744 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2745 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002746 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002747 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002748 File[] obbFiles = obbDir.listFiles();
2749 if (obbFiles != null) {
2750 final String obbDirName = obbDir.getAbsolutePath();
2751 for (File obb : obbFiles) {
2752 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2753 obbDirName, obb.getAbsolutePath(), output);
2754 }
2755 }
2756 }
2757 }
2758
Christopher Tate6853fcf2011-08-10 17:52:21 -07002759 private void finalizeBackup(OutputStream out) {
2760 try {
2761 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2762 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2763 out.write(eof);
2764 } catch (IOException e) {
2765 Slog.w(TAG, "Error attempting to finalize backup stream");
2766 }
2767 }
2768
Christopher Tate4a627c72011-04-01 14:43:32 -07002769 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2770 throws IOException {
2771 // Manifest format. All data are strings ending in LF:
2772 // BACKUP_MANIFEST_VERSION, currently 1
2773 //
2774 // Version 1:
2775 // package name
2776 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002777 // platform versionCode
2778 // getInstallerPackageName() for this package (maybe empty)
2779 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002780 // number of signatures == N
2781 // N*: signature byte array in ascii format per Signature.toCharsString()
2782 StringBuilder builder = new StringBuilder(4096);
2783 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2784
2785 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2786 printer.println(pkg.packageName);
2787 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002788 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2789
2790 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2791 printer.println((installerName != null) ? installerName : "");
2792
Christopher Tate4a627c72011-04-01 14:43:32 -07002793 printer.println(withApk ? "1" : "0");
2794 if (pkg.signatures == null) {
2795 printer.println("0");
2796 } else {
2797 printer.println(Integer.toString(pkg.signatures.length));
2798 for (Signature sig : pkg.signatures) {
2799 printer.println(sig.toCharsString());
2800 }
2801 }
2802
2803 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002804 outstream.write(builder.toString().getBytes());
2805 outstream.close();
2806 }
2807
2808 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002809 if (pkg != null) {
2810 final ApplicationInfo app = pkg.applicationInfo;
2811 if (app != null) {
2812 try {
2813 // unbind and tidy up even on timeout or failure, just in case
2814 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002815
Christopher Tateb0628bf2011-06-02 15:08:13 -07002816 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002817 if (app.uid != Process.SYSTEM_UID
2818 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002819 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002820 mActivityManager.killApplicationProcess(app.processName, app.uid);
2821 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002822 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002823 }
2824 } catch (RemoteException e) {
2825 Slog.d(TAG, "Lost app trying to shut down");
2826 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002827 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002828 }
2829 }
2830
2831 // wrappers for observer use
2832 void sendStartBackup() {
2833 if (mObserver != null) {
2834 try {
2835 mObserver.onStartBackup();
2836 } catch (RemoteException e) {
2837 Slog.w(TAG, "full backup observer went away: startBackup");
2838 mObserver = null;
2839 }
2840 }
2841 }
2842
2843 void sendOnBackupPackage(String name) {
2844 if (mObserver != null) {
2845 try {
2846 // TODO: use a more user-friendly name string
2847 mObserver.onBackupPackage(name);
2848 } catch (RemoteException e) {
2849 Slog.w(TAG, "full backup observer went away: backupPackage");
2850 mObserver = null;
2851 }
2852 }
2853 }
2854
2855 void sendEndBackup() {
2856 if (mObserver != null) {
2857 try {
2858 mObserver.onEndBackup();
2859 } catch (RemoteException e) {
2860 Slog.w(TAG, "full backup observer went away: endBackup");
2861 mObserver = null;
2862 }
2863 }
2864 }
2865 }
2866
2867
Christopher Tate75a99702011-05-18 16:28:19 -07002868 // ----- Full restore from a file/socket -----
2869
2870 // Description of a file in the restore datastream
2871 static class FileMetadata {
2872 String packageName; // name of the owning app
2873 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002874 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002875 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2876 String path; // subpath within the semantic domain
2877 long mode; // e.g. 0666 (actually int)
2878 long mtime; // last mod time, UTC time_t (actually int)
2879 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002880
2881 @Override
2882 public String toString() {
2883 StringBuilder sb = new StringBuilder(128);
2884 sb.append("FileMetadata{");
2885 sb.append(packageName); sb.append(',');
2886 sb.append(type); sb.append(',');
2887 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2888 sb.append(size);
2889 sb.append('}');
2890 return sb.toString();
2891 }
Christopher Tate75a99702011-05-18 16:28:19 -07002892 }
2893
2894 enum RestorePolicy {
2895 IGNORE,
2896 ACCEPT,
2897 ACCEPT_IF_APK
2898 }
2899
2900 class PerformFullRestoreTask implements Runnable {
2901 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002902 String mCurrentPassword;
2903 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002904 IFullBackupRestoreObserver mObserver;
2905 AtomicBoolean mLatchObject;
2906 IBackupAgent mAgent;
2907 String mAgentPackage;
2908 ApplicationInfo mTargetApp;
2909 ParcelFileDescriptor[] mPipes = null;
2910
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002911 long mBytes;
2912
Christopher Tate75a99702011-05-18 16:28:19 -07002913 // possible handling states for a given package in the restore dataset
2914 final HashMap<String, RestorePolicy> mPackagePolicies
2915 = new HashMap<String, RestorePolicy>();
2916
2917 // installer package names for each encountered app, derived from the manifests
2918 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2919
2920 // Signatures for a given package found in its manifest file
2921 final HashMap<String, Signature[]> mManifestSignatures
2922 = new HashMap<String, Signature[]>();
2923
2924 // Packages we've already wiped data on when restoring their first file
2925 final HashSet<String> mClearedPackages = new HashSet<String>();
2926
Christopher Tate728a1c42011-07-28 18:03:03 -07002927 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002928 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002929 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002930 mCurrentPassword = curPassword;
2931 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002932 mObserver = observer;
2933 mLatchObject = latch;
2934 mAgent = null;
2935 mAgentPackage = null;
2936 mTargetApp = null;
2937
2938 // Which packages we've already wiped data on. We prepopulate this
2939 // with a whitelist of packages known to be unclearable.
2940 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002941 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002942
Christopher Tate75a99702011-05-18 16:28:19 -07002943 }
2944
2945 class RestoreFileRunnable implements Runnable {
2946 IBackupAgent mAgent;
2947 FileMetadata mInfo;
2948 ParcelFileDescriptor mSocket;
2949 int mToken;
2950
2951 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2952 ParcelFileDescriptor socket, int token) throws IOException {
2953 mAgent = agent;
2954 mInfo = info;
2955 mToken = token;
2956
2957 // This class is used strictly for process-local binder invocations. The
2958 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2959 // do not automatically get a 'dup'ed descriptor that we can can continue
2960 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2961 // before proceeding to do the restore.
2962 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2963 }
2964
2965 @Override
2966 public void run() {
2967 try {
2968 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2969 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2970 mToken, mBackupManagerBinder);
2971 } catch (RemoteException e) {
2972 // never happens; this is used strictly for local binder calls
2973 }
2974 }
2975 }
2976
2977 @Override
2978 public void run() {
2979 Slog.i(TAG, "--- Performing full-dataset restore ---");
2980 sendStartRestore();
2981
Christopher Tateb0628bf2011-06-02 15:08:13 -07002982 // Are we able to restore shared-storage data?
2983 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002984 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002985 }
2986
Christopher Tate2efd2db2011-07-19 16:32:49 -07002987 FileInputStream rawInStream = null;
2988 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002989 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002990 if (hasBackupPassword()) {
2991 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2992 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2993 return;
2994 }
2995 }
2996
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002997 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002998 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002999 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3000 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003001
3002 // First, parse out the unencrypted/uncompressed header
3003 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003004 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003005 final InputStream in;
3006
3007 boolean okay = false;
3008 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3009 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003010 rawDataIn.readFully(streamHeader);
3011 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3012 if (Arrays.equals(magicBytes, streamHeader)) {
3013 // okay, header looks good. now parse out the rest of the fields.
3014 String s = readHeaderLine(rawInStream);
3015 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3016 // okay, it's a version we recognize
3017 s = readHeaderLine(rawInStream);
3018 compressed = (Integer.parseInt(s) != 0);
3019 s = readHeaderLine(rawInStream);
3020 if (s.equals("none")) {
3021 // no more header to parse; we're good to go
3022 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003023 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003024 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3025 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003026 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003027 }
3028 } else Slog.w(TAG, "Archive is encrypted but no password given");
3029 } else Slog.w(TAG, "Wrong header version: " + s);
3030 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003031
3032 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003033 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003034 return;
3035 }
3036
3037 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003038 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003039
3040 boolean didRestore;
3041 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003042 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003043 } while (didRestore);
3044
Christopher Tatec58efa62011-08-01 19:20:14 -07003045 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003046 } catch (IOException e) {
3047 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003048 } finally {
3049 tearDownPipes();
3050 tearDownAgent(mTargetApp);
3051
3052 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003053 if (rawDataIn != null) rawDataIn.close();
3054 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003055 mInputFile.close();
3056 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003057 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003058 /* nothing we can do about this */
3059 }
3060 synchronized (mCurrentOpLock) {
3061 mCurrentOperations.clear();
3062 }
3063 synchronized (mLatchObject) {
3064 mLatchObject.set(true);
3065 mLatchObject.notifyAll();
3066 }
3067 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003068 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003069 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003070 }
3071 }
3072
Christopher Tate7bdb0962011-07-13 19:30:21 -07003073 String readHeaderLine(InputStream in) throws IOException {
3074 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003075 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003076 while ((c = in.read()) >= 0) {
3077 if (c == '\n') break; // consume and discard the newlines
3078 buffer.append((char)c);
3079 }
3080 return buffer.toString();
3081 }
3082
Christopher Tate2efd2db2011-07-19 16:32:49 -07003083 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3084 InputStream result = null;
3085 try {
3086 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3087
3088 String userSaltHex = readHeaderLine(rawInStream); // 5
3089 byte[] userSalt = hexToByteArray(userSaltHex);
3090
3091 String ckSaltHex = readHeaderLine(rawInStream); // 6
3092 byte[] ckSalt = hexToByteArray(ckSaltHex);
3093
3094 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3095 String userIvHex = readHeaderLine(rawInStream); // 8
3096
3097 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3098
3099 // decrypt the master key blob
3100 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003101 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003102 rounds);
3103 byte[] IV = hexToByteArray(userIvHex);
3104 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3105 c.init(Cipher.DECRYPT_MODE,
3106 new SecretKeySpec(userKey.getEncoded(), "AES"),
3107 ivSpec);
3108 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3109 byte[] mkBlob = c.doFinal(mkCipher);
3110
3111 // first, the master key IV
3112 int offset = 0;
3113 int len = mkBlob[offset++];
3114 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3115 offset += len;
3116 // then the master key itself
3117 len = mkBlob[offset++];
3118 byte[] mk = Arrays.copyOfRange(mkBlob,
3119 offset, offset + len);
3120 offset += len;
3121 // and finally the master key checksum hash
3122 len = mkBlob[offset++];
3123 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3124 offset, offset + len);
3125
3126 // now validate the decrypted master key against the checksum
3127 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3128 if (Arrays.equals(calculatedCk, mkChecksum)) {
3129 ivSpec = new IvParameterSpec(IV);
3130 c.init(Cipher.DECRYPT_MODE,
3131 new SecretKeySpec(mk, "AES"),
3132 ivSpec);
3133 // Only if all of the above worked properly will 'result' be assigned
3134 result = new CipherInputStream(rawInStream, c);
3135 } else Slog.w(TAG, "Incorrect password");
3136 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3137 } catch (InvalidAlgorithmParameterException e) {
3138 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3139 } catch (BadPaddingException e) {
3140 // This case frequently occurs when the wrong password is used to decrypt
3141 // the master key. Use the identical "incorrect password" log text as is
3142 // used in the checksum failure log in order to avoid providing additional
3143 // information to an attacker.
3144 Slog.w(TAG, "Incorrect password");
3145 } catch (IllegalBlockSizeException e) {
3146 Slog.w(TAG, "Invalid block size in master key");
3147 } catch (NoSuchAlgorithmException e) {
3148 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3149 } catch (NoSuchPaddingException e) {
3150 Slog.e(TAG, "Needed padding mechanism unavailable!");
3151 } catch (InvalidKeyException e) {
3152 Slog.w(TAG, "Illegal password; aborting");
3153 } catch (NumberFormatException e) {
3154 Slog.w(TAG, "Can't parse restore data header");
3155 } catch (IOException e) {
3156 Slog.w(TAG, "Can't read input header");
3157 }
3158
3159 return result;
3160 }
3161
Christopher Tate75a99702011-05-18 16:28:19 -07003162 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3163 FileMetadata info;
3164 try {
3165 info = readTarHeaders(instream);
3166 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003167 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003168 dumpFileMetadata(info);
3169 }
3170
3171 final String pkg = info.packageName;
3172 if (!pkg.equals(mAgentPackage)) {
3173 // okay, change in package; set up our various
3174 // bookkeeping if we haven't seen it yet
3175 if (!mPackagePolicies.containsKey(pkg)) {
3176 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3177 }
3178
3179 // Clean up the previous agent relationship if necessary,
3180 // and let the observer know we're considering a new app.
3181 if (mAgent != null) {
3182 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3183 tearDownPipes();
3184 tearDownAgent(mTargetApp);
3185 mTargetApp = null;
3186 mAgentPackage = null;
3187 }
3188 }
3189
3190 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3191 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3192 mPackageInstallers.put(pkg, info.installerPackageName);
3193 // We've read only the manifest content itself at this point,
3194 // so consume the footer before looping around to the next
3195 // input file
3196 skipTarPadding(info.size, instream);
3197 sendOnRestorePackage(pkg);
3198 } else {
3199 // Non-manifest, so it's actual file data. Is this a package
3200 // we're ignoring?
3201 boolean okay = true;
3202 RestorePolicy policy = mPackagePolicies.get(pkg);
3203 switch (policy) {
3204 case IGNORE:
3205 okay = false;
3206 break;
3207
3208 case ACCEPT_IF_APK:
3209 // If we're in accept-if-apk state, then the first file we
3210 // see MUST be the apk.
3211 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3212 if (DEBUG) Slog.d(TAG, "APK file; installing");
3213 // Try to install the app.
3214 String installerName = mPackageInstallers.get(pkg);
3215 okay = installApk(info, installerName, instream);
3216 // good to go; promote to ACCEPT
3217 mPackagePolicies.put(pkg, (okay)
3218 ? RestorePolicy.ACCEPT
3219 : RestorePolicy.IGNORE);
3220 // At this point we've consumed this file entry
3221 // ourselves, so just strip the tar footer and
3222 // go on to the next file in the input stream
3223 skipTarPadding(info.size, instream);
3224 return true;
3225 } else {
3226 // File data before (or without) the apk. We can't
3227 // handle it coherently in this case so ignore it.
3228 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3229 okay = false;
3230 }
3231 break;
3232
3233 case ACCEPT:
3234 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3235 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3236 // we can take the data without the apk, so we
3237 // *want* to do so. skip the apk by declaring this
3238 // one file not-okay without changing the restore
3239 // policy for the package.
3240 okay = false;
3241 }
3242 break;
3243
3244 default:
3245 // Something has gone dreadfully wrong when determining
3246 // the restore policy from the manifest. Ignore the
3247 // rest of this package's data.
3248 Slog.e(TAG, "Invalid policy from manifest");
3249 okay = false;
3250 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3251 break;
3252 }
3253
3254 // If the policy is satisfied, go ahead and set up to pipe the
3255 // data to the agent.
3256 if (DEBUG && okay && mAgent != null) {
3257 Slog.i(TAG, "Reusing existing agent instance");
3258 }
3259 if (okay && mAgent == null) {
3260 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3261
3262 try {
3263 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3264
3265 // If we haven't sent any data to this app yet, we probably
3266 // need to clear it first. Check that.
3267 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003268 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003269 // responsible for coherently managing a full
3270 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003271 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003272 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3273 clearApplicationDataSynchronous(pkg);
3274 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003275 if (DEBUG) Slog.d(TAG, "backup agent ("
3276 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003277 }
3278 mClearedPackages.add(pkg);
3279 } else {
3280 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3281 }
3282
3283 // All set; now set up the IPC and launch the agent
3284 setUpPipes();
3285 mAgent = bindToAgentSynchronous(mTargetApp,
3286 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3287 mAgentPackage = pkg;
3288 } catch (IOException e) {
3289 // fall through to error handling
3290 } catch (NameNotFoundException e) {
3291 // fall through to error handling
3292 }
3293
3294 if (mAgent == null) {
3295 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3296 okay = false;
3297 tearDownPipes();
3298 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3299 }
3300 }
3301
3302 // Sanity check: make sure we never give data to the wrong app. This
3303 // should never happen but a little paranoia here won't go amiss.
3304 if (okay && !pkg.equals(mAgentPackage)) {
3305 Slog.e(TAG, "Restoring data for " + pkg
3306 + " but agent is for " + mAgentPackage);
3307 okay = false;
3308 }
3309
3310 // At this point we have an agent ready to handle the full
3311 // restore data as well as a pipe for sending data to
3312 // that agent. Tell the agent to start reading from the
3313 // pipe.
3314 if (okay) {
3315 boolean agentSuccess = true;
3316 long toCopy = info.size;
3317 final int token = generateToken();
3318 try {
3319 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3320 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003321 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003322 // fire up the app's agent listening on the socket. If
3323 // the agent is running in the system process we can't
3324 // just invoke it asynchronously, so we provide a thread
3325 // for it here.
3326 if (mTargetApp.processName.equals("system")) {
3327 Slog.d(TAG, "system process agent - spinning a thread");
3328 RestoreFileRunnable runner = new RestoreFileRunnable(
3329 mAgent, info, mPipes[0], token);
3330 new Thread(runner).start();
3331 } else {
3332 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3333 info.domain, info.path, info.mode, info.mtime,
3334 token, mBackupManagerBinder);
3335 }
3336 } catch (IOException e) {
3337 // couldn't dup the socket for a process-local restore
3338 Slog.d(TAG, "Couldn't establish restore");
3339 agentSuccess = false;
3340 okay = false;
3341 } catch (RemoteException e) {
3342 // whoops, remote agent went away. We'll eat the content
3343 // ourselves, then, and not copy it over.
3344 Slog.e(TAG, "Agent crashed during full restore");
3345 agentSuccess = false;
3346 okay = false;
3347 }
3348
3349 // Copy over the data if the agent is still good
3350 if (okay) {
3351 boolean pipeOkay = true;
3352 FileOutputStream pipe = new FileOutputStream(
3353 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003354 while (toCopy > 0) {
3355 int toRead = (toCopy > buffer.length)
3356 ? buffer.length : (int)toCopy;
3357 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003358 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003359 if (nRead <= 0) break;
3360 toCopy -= nRead;
3361
3362 // send it to the output pipe as long as things
3363 // are still good
3364 if (pipeOkay) {
3365 try {
3366 pipe.write(buffer, 0, nRead);
3367 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003368 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003369 pipeOkay = false;
3370 }
3371 }
3372 }
3373
3374 // done sending that file! Now we just need to consume
3375 // the delta from info.size to the end of block.
3376 skipTarPadding(info.size, instream);
3377
3378 // and now that we've sent it all, wait for the remote
3379 // side to acknowledge receipt
3380 agentSuccess = waitUntilOperationComplete(token);
3381 }
3382
3383 // okay, if the remote end failed at any point, deal with
3384 // it by ignoring the rest of the restore on it
3385 if (!agentSuccess) {
3386 mBackupHandler.removeMessages(MSG_TIMEOUT);
3387 tearDownPipes();
3388 tearDownAgent(mTargetApp);
3389 mAgent = null;
3390 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3391 }
3392 }
3393
3394 // Problems setting up the agent communication, or an already-
3395 // ignored package: skip to the next tar stream entry by
3396 // reading and discarding this file.
3397 if (!okay) {
3398 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3399 long bytesToConsume = (info.size + 511) & ~511;
3400 while (bytesToConsume > 0) {
3401 int toRead = (bytesToConsume > buffer.length)
3402 ? buffer.length : (int)bytesToConsume;
3403 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003404 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003405 if (nRead <= 0) break;
3406 bytesToConsume -= nRead;
3407 }
3408 }
3409 }
3410 }
3411 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003412 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003413 // treat as EOF
3414 info = null;
3415 }
3416
3417 return (info != null);
3418 }
3419
3420 void setUpPipes() throws IOException {
3421 mPipes = ParcelFileDescriptor.createPipe();
3422 }
3423
3424 void tearDownPipes() {
3425 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003426 try {
3427 mPipes[0].close();
3428 mPipes[0] = null;
3429 mPipes[1].close();
3430 mPipes[1] = null;
3431 } catch (IOException e) {
3432 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003433 }
3434 mPipes = null;
3435 }
3436 }
3437
3438 void tearDownAgent(ApplicationInfo app) {
3439 if (mAgent != null) {
3440 try {
3441 // unbind and tidy up even on timeout or failure, just in case
3442 mActivityManager.unbindBackupAgent(app);
3443
3444 // The agent was running with a stub Application object, so shut it down.
3445 // !!! We hardcode the confirmation UI's package name here rather than use a
3446 // manifest flag! TODO something less direct.
3447 if (app.uid != Process.SYSTEM_UID
3448 && !app.packageName.equals("com.android.backupconfirm")) {
3449 if (DEBUG) Slog.d(TAG, "Killing host process");
3450 mActivityManager.killApplicationProcess(app.processName, app.uid);
3451 } else {
3452 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3453 }
3454 } catch (RemoteException e) {
3455 Slog.d(TAG, "Lost app trying to shut down");
3456 }
3457 mAgent = null;
3458 }
3459 }
3460
3461 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3462 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003463 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003464 int mResult;
3465
3466 public void reset() {
3467 synchronized (mDone) {
3468 mDone.set(false);
3469 }
3470 }
3471
3472 public void waitForCompletion() {
3473 synchronized (mDone) {
3474 while (mDone.get() == false) {
3475 try {
3476 mDone.wait();
3477 } catch (InterruptedException e) { }
3478 }
3479 }
3480 }
3481
3482 int getResult() {
3483 return mResult;
3484 }
3485
3486 @Override
3487 public void packageInstalled(String packageName, int returnCode)
3488 throws RemoteException {
3489 synchronized (mDone) {
3490 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003491 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003492 mDone.set(true);
3493 mDone.notifyAll();
3494 }
3495 }
3496 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003497
3498 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3499 final AtomicBoolean mDone = new AtomicBoolean();
3500 int mResult;
3501
3502 public void reset() {
3503 synchronized (mDone) {
3504 mDone.set(false);
3505 }
3506 }
3507
3508 public void waitForCompletion() {
3509 synchronized (mDone) {
3510 while (mDone.get() == false) {
3511 try {
3512 mDone.wait();
3513 } catch (InterruptedException e) { }
3514 }
3515 }
3516 }
3517
3518 @Override
3519 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3520 synchronized (mDone) {
3521 mResult = returnCode;
3522 mDone.set(true);
3523 mDone.notifyAll();
3524 }
3525 }
3526 }
3527
Christopher Tate75a99702011-05-18 16:28:19 -07003528 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003529 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003530
3531 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3532 boolean okay = true;
3533
3534 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3535
3536 // The file content is an .apk file. Copy it out to a staging location and
3537 // attempt to install it.
3538 File apkFile = new File(mDataDir, info.packageName);
3539 try {
3540 FileOutputStream apkStream = new FileOutputStream(apkFile);
3541 byte[] buffer = new byte[32 * 1024];
3542 long size = info.size;
3543 while (size > 0) {
3544 long toRead = (buffer.length < size) ? buffer.length : size;
3545 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003546 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003547 apkStream.write(buffer, 0, didRead);
3548 size -= didRead;
3549 }
3550 apkStream.close();
3551
3552 // make sure the installer can read it
3553 apkFile.setReadable(true, false);
3554
3555 // Now install it
3556 Uri packageUri = Uri.fromFile(apkFile);
3557 mInstallObserver.reset();
3558 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003559 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3560 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003561 mInstallObserver.waitForCompletion();
3562
3563 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3564 // The only time we continue to accept install of data even if the
3565 // apk install failed is if we had already determined that we could
3566 // accept the data regardless.
3567 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3568 okay = false;
3569 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003570 } else {
3571 // Okay, the install succeeded. Make sure it was the right app.
3572 boolean uninstall = false;
3573 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3574 Slog.w(TAG, "Restore stream claimed to include apk for "
3575 + info.packageName + " but apk was really "
3576 + mInstallObserver.mPackageName);
3577 // delete the package we just put in place; it might be fraudulent
3578 okay = false;
3579 uninstall = true;
3580 } else {
3581 try {
3582 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3583 PackageManager.GET_SIGNATURES);
3584 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3585 Slog.w(TAG, "Restore stream contains apk of package "
3586 + info.packageName + " but it disallows backup/restore");
3587 okay = false;
3588 } else {
3589 // So far so good -- do the signatures match the manifest?
3590 Signature[] sigs = mManifestSignatures.get(info.packageName);
3591 if (!signaturesMatch(sigs, pkg)) {
3592 Slog.w(TAG, "Installed app " + info.packageName
3593 + " signatures do not match restore manifest");
3594 okay = false;
3595 uninstall = true;
3596 }
3597 }
3598 } catch (NameNotFoundException e) {
3599 Slog.w(TAG, "Install of package " + info.packageName
3600 + " succeeded but now not found");
3601 okay = false;
3602 }
3603 }
3604
3605 // If we're not okay at this point, we need to delete the package
3606 // that we just installed.
3607 if (uninstall) {
3608 mDeleteObserver.reset();
3609 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3610 mDeleteObserver, 0);
3611 mDeleteObserver.waitForCompletion();
3612 }
Christopher Tate75a99702011-05-18 16:28:19 -07003613 }
3614 } catch (IOException e) {
3615 Slog.e(TAG, "Unable to transcribe restored apk for install");
3616 okay = false;
3617 } finally {
3618 apkFile.delete();
3619 }
3620
3621 return okay;
3622 }
3623
3624 // Given an actual file content size, consume the post-content padding mandated
3625 // by the tar format.
3626 void skipTarPadding(long size, InputStream instream) throws IOException {
3627 long partial = (size + 512) % 512;
3628 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003629 final int needed = 512 - (int)partial;
3630 byte[] buffer = new byte[needed];
3631 if (readExactly(instream, buffer, 0, needed) == needed) {
3632 mBytes += needed;
3633 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003634 }
3635 }
3636
3637 // Returns a policy constant; takes a buffer arg to reduce memory churn
3638 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3639 throws IOException {
3640 // Fail on suspiciously large manifest files
3641 if (info.size > 64 * 1024) {
3642 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3643 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003644
Christopher Tate75a99702011-05-18 16:28:19 -07003645 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003646 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3647 mBytes += info.size;
3648 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003649
3650 RestorePolicy policy = RestorePolicy.IGNORE;
3651 String[] str = new String[1];
3652 int offset = 0;
3653
3654 try {
3655 offset = extractLine(buffer, offset, str);
3656 int version = Integer.parseInt(str[0]);
3657 if (version == BACKUP_MANIFEST_VERSION) {
3658 offset = extractLine(buffer, offset, str);
3659 String manifestPackage = str[0];
3660 // TODO: handle <original-package>
3661 if (manifestPackage.equals(info.packageName)) {
3662 offset = extractLine(buffer, offset, str);
3663 version = Integer.parseInt(str[0]); // app version
3664 offset = extractLine(buffer, offset, str);
3665 int platformVersion = Integer.parseInt(str[0]);
3666 offset = extractLine(buffer, offset, str);
3667 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3668 offset = extractLine(buffer, offset, str);
3669 boolean hasApk = str[0].equals("1");
3670 offset = extractLine(buffer, offset, str);
3671 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003672 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003673 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003674 for (int i = 0; i < numSigs; i++) {
3675 offset = extractLine(buffer, offset, str);
3676 sigs[i] = new Signature(str[0]);
3677 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003678 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003679
3680 // Okay, got the manifest info we need...
3681 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003682 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3683 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003684 // Fall through to IGNORE if the app explicitly disallows backup
3685 final int flags = pkgInfo.applicationInfo.flags;
3686 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003687 // Restore system-uid-space packages only if they have
3688 // defined a custom backup agent
3689 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3690 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3691 // Verify signatures against any installed version; if they
3692 // don't match, then we fall though and ignore the data. The
3693 // signatureMatch() method explicitly ignores the signature
3694 // check for packages installed on the system partition, because
3695 // such packages are signed with the platform cert instead of
3696 // the app developer's cert, so they're different on every
3697 // device.
3698 if (signaturesMatch(sigs, pkgInfo)) {
3699 if (pkgInfo.versionCode >= version) {
3700 Slog.i(TAG, "Sig + version match; taking data");
3701 policy = RestorePolicy.ACCEPT;
3702 } else {
3703 // The data is from a newer version of the app than
3704 // is presently installed. That means we can only
3705 // use it if the matching apk is also supplied.
3706 Slog.d(TAG, "Data version " + version
3707 + " is newer than installed version "
3708 + pkgInfo.versionCode + " - requiring apk");
3709 policy = RestorePolicy.ACCEPT_IF_APK;
3710 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003711 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003712 Slog.w(TAG, "Restore manifest signatures do not match "
3713 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003714 }
Christopher Tate75a99702011-05-18 16:28:19 -07003715 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003716 Slog.w(TAG, "Package " + info.packageName
3717 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003718 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003719 } else {
3720 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3721 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003722 }
3723 } catch (NameNotFoundException e) {
3724 // Okay, the target app isn't installed. We can process
3725 // the restore properly only if the dataset provides the
3726 // apk file and we can successfully install it.
3727 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3728 + " not installed; requiring apk in dataset");
3729 policy = RestorePolicy.ACCEPT_IF_APK;
3730 }
3731
3732 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3733 Slog.i(TAG, "Cannot restore package " + info.packageName
3734 + " without the matching .apk");
3735 }
3736 } else {
3737 Slog.i(TAG, "Missing signature on backed-up package "
3738 + info.packageName);
3739 }
3740 } else {
3741 Slog.i(TAG, "Expected package " + info.packageName
3742 + " but restore manifest claims " + manifestPackage);
3743 }
3744 } else {
3745 Slog.i(TAG, "Unknown restore manifest version " + version
3746 + " for package " + info.packageName);
3747 }
3748 } catch (NumberFormatException e) {
3749 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003750 } catch (IllegalArgumentException e) {
3751 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003752 }
3753
3754 return policy;
3755 }
3756
3757 // Builds a line from a byte buffer starting at 'offset', and returns
3758 // the index of the next unconsumed data in the buffer.
3759 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3760 final int end = buffer.length;
3761 if (offset >= end) throw new IOException("Incomplete data");
3762
3763 int pos;
3764 for (pos = offset; pos < end; pos++) {
3765 byte c = buffer[pos];
3766 // at LF we declare end of line, and return the next char as the
3767 // starting point for the next time through
3768 if (c == '\n') {
3769 break;
3770 }
3771 }
3772 outStr[0] = new String(buffer, offset, pos - offset);
3773 pos++; // may be pointing an extra byte past the end but that's okay
3774 return pos;
3775 }
3776
3777 void dumpFileMetadata(FileMetadata info) {
3778 if (DEBUG) {
3779 StringBuilder b = new StringBuilder(128);
3780
3781 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003782 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003783 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3784 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3785 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3786 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3787 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3788 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3789 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3790 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3791 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3792 b.append(String.format(" %9d ", info.size));
3793
3794 Date stamp = new Date(info.mtime);
3795 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3796
3797 b.append(info.packageName);
3798 b.append(" :: ");
3799 b.append(info.domain);
3800 b.append(" :: ");
3801 b.append(info.path);
3802
3803 Slog.i(TAG, b.toString());
3804 }
3805 }
3806 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3807 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3808 byte[] block = new byte[512];
3809 FileMetadata info = null;
3810
3811 boolean gotHeader = readTarHeader(instream, block);
3812 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003813 try {
3814 // okay, presume we're okay, and extract the various metadata
3815 info = new FileMetadata();
3816 info.size = extractRadix(block, 124, 12, 8);
3817 info.mtime = extractRadix(block, 136, 12, 8);
3818 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003819
Christopher Tate2efd2db2011-07-19 16:32:49 -07003820 info.path = extractString(block, 345, 155); // prefix
3821 String path = extractString(block, 0, 100);
3822 if (path.length() > 0) {
3823 if (info.path.length() > 0) info.path += '/';
3824 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003825 }
Christopher Tate75a99702011-05-18 16:28:19 -07003826
Christopher Tate2efd2db2011-07-19 16:32:49 -07003827 // tar link indicator field: 1 byte at offset 156 in the header.
3828 int typeChar = block[156];
3829 if (typeChar == 'x') {
3830 // pax extended header, so we need to read that
3831 gotHeader = readPaxExtendedHeader(instream, info);
3832 if (gotHeader) {
3833 // and after a pax extended header comes another real header -- read
3834 // that to find the real file type
3835 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003836 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003837 if (!gotHeader) throw new IOException("Bad or missing pax header");
3838
3839 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003840 }
Christopher Tate75a99702011-05-18 16:28:19 -07003841
Christopher Tate2efd2db2011-07-19 16:32:49 -07003842 switch (typeChar) {
3843 case '0': info.type = BackupAgent.TYPE_FILE; break;
3844 case '5': {
3845 info.type = BackupAgent.TYPE_DIRECTORY;
3846 if (info.size != 0) {
3847 Slog.w(TAG, "Directory entry with nonzero size in header");
3848 info.size = 0;
3849 }
3850 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003851 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003852 case 0: {
3853 // presume EOF
3854 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3855 return null;
3856 }
3857 default: {
3858 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3859 throw new IOException("Unknown entity type " + typeChar);
3860 }
Christopher Tate75a99702011-05-18 16:28:19 -07003861 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003862
3863 // Parse out the path
3864 //
3865 // first: apps/shared/unrecognized
3866 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3867 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3868 // File in shared storage. !!! TODO: implement this.
3869 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003870 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003871 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3872 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3873 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3874 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3875 // App content! Parse out the package name and domain
3876
3877 // strip the apps/ prefix
3878 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3879
3880 // extract the package name
3881 int slash = info.path.indexOf('/');
3882 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3883 info.packageName = info.path.substring(0, slash);
3884 info.path = info.path.substring(slash+1);
3885
3886 // if it's a manifest we're done, otherwise parse out the domains
3887 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3888 slash = info.path.indexOf('/');
3889 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3890 info.domain = info.path.substring(0, slash);
3891 // validate that it's one of the domains we understand
3892 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3893 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3894 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3895 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3896 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3897 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3898 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3899 throw new IOException("Unrecognized domain " + info.domain);
3900 }
3901
3902 info.path = info.path.substring(slash + 1);
3903 }
3904 }
3905 } catch (IOException e) {
3906 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003907 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003908 HEXLOG(block);
3909 }
3910 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003911 }
3912 }
3913 return info;
3914 }
3915
Christopher Tate2efd2db2011-07-19 16:32:49 -07003916 private void HEXLOG(byte[] block) {
3917 int offset = 0;
3918 int todo = block.length;
3919 StringBuilder buf = new StringBuilder(64);
3920 while (todo > 0) {
3921 buf.append(String.format("%04x ", offset));
3922 int numThisLine = (todo > 16) ? 16 : todo;
3923 for (int i = 0; i < numThisLine; i++) {
3924 buf.append(String.format("%02x ", block[offset+i]));
3925 }
3926 Slog.i("hexdump", buf.toString());
3927 buf.setLength(0);
3928 todo -= numThisLine;
3929 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003930 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003931 }
3932
Christopher Tate6853fcf2011-08-10 17:52:21 -07003933 // Read exactly the given number of bytes into a buffer at the stated offset.
3934 // Returns false if EOF is encountered before the requested number of bytes
3935 // could be read.
3936 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3937 throws IOException {
3938 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3939
3940 int soFar = 0;
3941 while (soFar < size) {
3942 int nRead = in.read(buffer, offset + soFar, size - soFar);
3943 if (nRead <= 0) {
3944 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3945 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003946 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003947 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003948 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003949 return soFar;
3950 }
3951
3952 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3953 final int got = readExactly(instream, block, 0, 512);
3954 if (got == 0) return false; // Clean EOF
3955 if (got < 512) throw new IOException("Unable to read full block header");
3956 mBytes += 512;
3957 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003958 }
3959
3960 // overwrites 'info' fields based on the pax extended header
3961 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3962 throws IOException {
3963 // We should never see a pax extended header larger than this
3964 if (info.size > 32*1024) {
3965 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3966 + " - aborting");
3967 throw new IOException("Sanity failure: pax header size " + info.size);
3968 }
3969
3970 // read whole blocks, not just the content size
3971 int numBlocks = (int)((info.size + 511) >> 9);
3972 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003973 if (readExactly(instream, data, 0, data.length) < data.length) {
3974 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003975 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003976 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003977
3978 final int contentSize = (int) info.size;
3979 int offset = 0;
3980 do {
3981 // extract the line at 'offset'
3982 int eol = offset+1;
3983 while (eol < contentSize && data[eol] != ' ') eol++;
3984 if (eol >= contentSize) {
3985 // error: we just hit EOD looking for the end of the size field
3986 throw new IOException("Invalid pax data");
3987 }
3988 // eol points to the space between the count and the key
3989 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3990 int key = eol + 1; // start of key=value
3991 eol = offset + linelen - 1; // trailing LF
3992 int value;
3993 for (value = key+1; data[value] != '=' && value <= eol; value++);
3994 if (value > eol) {
3995 throw new IOException("Invalid pax declaration");
3996 }
3997
3998 // pax requires that key/value strings be in UTF-8
3999 String keyStr = new String(data, key, value-key, "UTF-8");
4000 // -1 to strip the trailing LF
4001 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4002
4003 if ("path".equals(keyStr)) {
4004 info.path = valStr;
4005 } else if ("size".equals(keyStr)) {
4006 info.size = Long.parseLong(valStr);
4007 } else {
4008 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4009 }
4010
4011 offset += linelen;
4012 } while (offset < contentSize);
4013
4014 return true;
4015 }
4016
4017 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4018 throws IOException {
4019 long value = 0;
4020 final int end = offset + maxChars;
4021 for (int i = offset; i < end; i++) {
4022 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004023 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004024 if (b == 0 || b == ' ') break;
4025 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004026 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004027 }
4028 value = radix * value + (b - '0');
4029 }
4030 return value;
4031 }
4032
4033 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4034 final int end = offset + maxChars;
4035 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004036 // tar string fields terminate early with a NUL
4037 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004038 return new String(data, offset, eos-offset, "US-ASCII");
4039 }
4040
4041 void sendStartRestore() {
4042 if (mObserver != null) {
4043 try {
4044 mObserver.onStartRestore();
4045 } catch (RemoteException e) {
4046 Slog.w(TAG, "full restore observer went away: startRestore");
4047 mObserver = null;
4048 }
4049 }
4050 }
4051
4052 void sendOnRestorePackage(String name) {
4053 if (mObserver != null) {
4054 try {
4055 // TODO: use a more user-friendly name string
4056 mObserver.onRestorePackage(name);
4057 } catch (RemoteException e) {
4058 Slog.w(TAG, "full restore observer went away: restorePackage");
4059 mObserver = null;
4060 }
4061 }
4062 }
4063
4064 void sendEndRestore() {
4065 if (mObserver != null) {
4066 try {
4067 mObserver.onEndRestore();
4068 } catch (RemoteException e) {
4069 Slog.w(TAG, "full restore observer went away: endRestore");
4070 mObserver = null;
4071 }
4072 }
4073 }
4074 }
4075
Christopher Tatedf01dea2009-06-09 20:45:02 -07004076 // ----- Restore handling -----
4077
Christopher Tate78dd4a72009-11-04 11:49:08 -08004078 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4079 // If the target resides on the system partition, we allow it to restore
4080 // data from the like-named package in a restore set even if the signatures
4081 // do not match. (Unlike general applications, those flashed to the system
4082 // partition will be signed with the device's platform certificate, so on
4083 // different phones the same system app will have different signatures.)
4084 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004085 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004086 return true;
4087 }
4088
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004089 // Allow unsigned apps, but not signed on one device and unsigned on the other
4090 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004091 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004092 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004093 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004094 if ((storedSigs == null || storedSigs.length == 0)
4095 && (deviceSigs == null || deviceSigs.length == 0)) {
4096 return true;
4097 }
4098 if (storedSigs == null || deviceSigs == null) {
4099 return false;
4100 }
4101
Christopher Tateabce4e82009-06-18 18:35:32 -07004102 // !!! TODO: this demands that every stored signature match one
4103 // that is present on device, and does not demand the converse.
4104 // Is this this right policy?
4105 int nStored = storedSigs.length;
4106 int nDevice = deviceSigs.length;
4107
4108 for (int i=0; i < nStored; i++) {
4109 boolean match = false;
4110 for (int j=0; j < nDevice; j++) {
4111 if (storedSigs[i].equals(deviceSigs[j])) {
4112 match = true;
4113 break;
4114 }
4115 }
4116 if (!match) {
4117 return false;
4118 }
4119 }
4120 return true;
4121 }
4122
Christopher Tate2982d062011-09-06 20:35:24 -07004123 enum RestoreState {
4124 INITIAL,
4125 DOWNLOAD_DATA,
4126 PM_METADATA,
4127 RUNNING_QUEUE,
4128 FINAL
4129 }
4130
4131 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004132 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004133 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004134 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004135 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004136 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004137 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004138 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004139 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004140 private long mStartRealtime;
4141 private PackageManagerBackupAgent mPmAgent;
4142 private List<PackageInfo> mAgentPackages;
4143 private ArrayList<PackageInfo> mRestorePackages;
4144 private RestoreState mCurrentState;
4145 private int mCount;
4146 private boolean mFinished;
4147 private int mStatus;
4148 private File mBackupDataName;
4149 private File mNewStateName;
4150 private File mSavedStateName;
4151 private ParcelFileDescriptor mBackupData;
4152 private ParcelFileDescriptor mNewState;
4153 private PackageInfo mCurrentPackage;
4154
Christopher Tatedf01dea2009-06-09 20:45:02 -07004155
Christopher Tate5cbbf562009-06-22 16:44:51 -07004156 class RestoreRequest {
4157 public PackageInfo app;
4158 public int storedAppVersion;
4159
4160 RestoreRequest(PackageInfo _app, int _version) {
4161 app = _app;
4162 storedAppVersion = _version;
4163 }
4164 }
4165
Christopher Tate44a27902010-01-27 17:15:49 -08004166 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004167 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004168 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004169 mCurrentState = RestoreState.INITIAL;
4170 mFinished = false;
4171 mPmAgent = null;
4172
Christopher Tatedf01dea2009-06-09 20:45:02 -07004173 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004174 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004175 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004176 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004177 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004178 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004179
Christopher Tate284f1bb2011-07-07 14:31:18 -07004180 if (filterSet != null) {
4181 mFilterSet = new HashSet<String>();
4182 for (String pkg : filterSet) {
4183 mFilterSet.add(pkg);
4184 }
4185 } else {
4186 mFilterSet = null;
4187 }
4188
Christopher Tate5cb400b2009-06-25 16:03:14 -07004189 try {
4190 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4191 } catch (RemoteException e) {
4192 // can't happen; the transport is local
4193 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004194 }
4195
Christopher Tate2982d062011-09-06 20:35:24 -07004196 // Execute one tick of whatever state machine the task implements
4197 @Override
4198 public void execute() {
4199 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4200 switch (mCurrentState) {
4201 case INITIAL:
4202 beginRestore();
4203 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004204
Christopher Tate2982d062011-09-06 20:35:24 -07004205 case DOWNLOAD_DATA:
4206 downloadRestoreData();
4207 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004208
Christopher Tate2982d062011-09-06 20:35:24 -07004209 case PM_METADATA:
4210 restorePmMetadata();
4211 break;
4212
4213 case RUNNING_QUEUE:
4214 restoreNextAgent();
4215 break;
4216
4217 case FINAL:
4218 if (!mFinished) finalizeRestore();
4219 else {
4220 Slog.e(TAG, "Duplicate finish");
4221 }
4222 mFinished = true;
4223 break;
4224 }
4225 }
4226
4227 // Initialize and set up for the PM metadata restore, which comes first
4228 void beginRestore() {
4229 // Don't account time doing the restore as inactivity of the app
4230 // that has opened a restore session.
4231 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4232
4233 // Assume error until we successfully init everything
4234 mStatus = BackupConstants.TRANSPORT_ERROR;
4235
Christopher Tatedf01dea2009-06-09 20:45:02 -07004236 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004237 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004238 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004239
Dan Egnorefe52642009-06-24 00:16:33 -07004240 // Get the list of all packages which have backup enabled.
4241 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004242 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004243 PackageInfo omPackage = new PackageInfo();
4244 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004245 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004246
Christopher Tate2982d062011-09-06 20:35:24 -07004247 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004248 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004249 // if there's a filter set, strip out anything that isn't
4250 // present before proceeding
4251 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004252 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4253 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004254 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004255 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004256 }
4257 }
Christopher Tate2982d062011-09-06 20:35:24 -07004258 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004259 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004260 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004261 Slog.i(TAG, " " + p);
4262 }
4263 }
4264 }
Christopher Tate2982d062011-09-06 20:35:24 -07004265 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004266 } else {
4267 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004268 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004269 }
Dan Egnorefe52642009-06-24 00:16:33 -07004270
Christopher Tate7d562ec2009-06-25 18:03:43 -07004271 // let the observer know that we're running
4272 if (mObserver != null) {
4273 try {
4274 // !!! TODO: get an actual count from the transport after
4275 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004276 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004277 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004278 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004279 mObserver = null;
4280 }
4281 }
Christopher Tate2982d062011-09-06 20:35:24 -07004282 } catch (RemoteException e) {
4283 // Something has gone catastrophically wrong with the transport
4284 Slog.e(TAG, "Error communicating with transport for restore");
4285 executeNextState(RestoreState.FINAL);
4286 return;
4287 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004288
Christopher Tate2982d062011-09-06 20:35:24 -07004289 mStatus = BackupConstants.TRANSPORT_OK;
4290 executeNextState(RestoreState.DOWNLOAD_DATA);
4291 }
4292
4293 void downloadRestoreData() {
4294 // Note that the download phase can be very time consuming, but we're executing
4295 // it inline here on the looper. This is "okay" because it is not calling out to
4296 // third party code; the transport is "trusted," and so we assume it is being a
4297 // good citizen and timing out etc when appropriate.
4298 //
4299 // TODO: when appropriate, move the download off the looper and rearrange the
4300 // error handling around that.
4301 try {
4302 mStatus = mTransport.startRestore(mToken,
4303 mRestorePackages.toArray(new PackageInfo[0]));
4304 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004305 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004306 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004307 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004308 return;
4309 }
Christopher Tate2982d062011-09-06 20:35:24 -07004310 } catch (RemoteException e) {
4311 Slog.e(TAG, "Error communicating with transport for restore");
4312 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4313 mStatus = BackupConstants.TRANSPORT_ERROR;
4314 executeNextState(RestoreState.FINAL);
4315 return;
4316 }
Dan Egnorefe52642009-06-24 00:16:33 -07004317
Christopher Tate2982d062011-09-06 20:35:24 -07004318 // Successful download of the data to be parceled out to the apps, so off we go.
4319 executeNextState(RestoreState.PM_METADATA);
4320 }
4321
4322 void restorePmMetadata() {
4323 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004324 String packageName = mTransport.nextRestorePackage();
4325 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004326 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004327 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004328 mStatus = BackupConstants.TRANSPORT_ERROR;
4329 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004330 return;
4331 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004332 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004333 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004334 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004335 mStatus = BackupConstants.TRANSPORT_OK;
4336 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004337 return;
4338 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004339 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004340 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004341 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004342 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004343 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004344 return;
4345 }
4346
4347 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004348 PackageInfo omPackage = new PackageInfo();
4349 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4350 mPmAgent = new PackageManagerBackupAgent(
4351 mPackageManager, mAgentPackages);
4352 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004353 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004354 // The PM agent called operationComplete() already, because our invocation
4355 // of it is process-local and therefore synchronous. That means that a
4356 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4357 // proceed with running the queue do we remove that pending message and
4358 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004359
Christopher Tate8c032472009-07-02 14:28:47 -07004360 // Verify that the backup set includes metadata. If not, we can't do
4361 // signature/version verification etc, so we simply do not proceed with
4362 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004363 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004364 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004365 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004366 "Package manager restore metadata missing");
4367 mStatus = BackupConstants.TRANSPORT_ERROR;
4368 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4369 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004370 return;
4371 }
Christopher Tate2982d062011-09-06 20:35:24 -07004372 } catch (RemoteException e) {
4373 Slog.e(TAG, "Error communicating with transport for restore");
4374 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4375 mStatus = BackupConstants.TRANSPORT_ERROR;
4376 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4377 executeNextState(RestoreState.FINAL);
4378 return;
4379 }
Christopher Tate8c032472009-07-02 14:28:47 -07004380
Christopher Tate2982d062011-09-06 20:35:24 -07004381 // Metadata is intact, so we can now run the restore queue. If we get here,
4382 // we have already enqueued the necessary next-step message on the looper.
4383 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004384
Christopher Tate2982d062011-09-06 20:35:24 -07004385 void restoreNextAgent() {
4386 try {
4387 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004388
Christopher Tate2982d062011-09-06 20:35:24 -07004389 if (packageName == null) {
4390 Slog.e(TAG, "Error getting next restore package");
4391 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4392 executeNextState(RestoreState.FINAL);
4393 return;
4394 } else if (packageName.equals("")) {
4395 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4396 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4397 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4398 executeNextState(RestoreState.FINAL);
4399 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004400 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004401
4402 if (mObserver != null) {
4403 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004404 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004405 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004406 Slog.d(TAG, "Restore observer died in onUpdate");
4407 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004408 }
4409 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004410
Christopher Tate2982d062011-09-06 20:35:24 -07004411 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4412 if (metaInfo == null) {
4413 Slog.e(TAG, "Missing metadata for " + packageName);
4414 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4415 "Package metadata missing");
4416 executeNextState(RestoreState.RUNNING_QUEUE);
4417 return;
Christopher Tate84725812010-02-04 15:52:40 -08004418 }
4419
Christopher Tate2982d062011-09-06 20:35:24 -07004420 PackageInfo packageInfo;
4421 try {
4422 int flags = PackageManager.GET_SIGNATURES;
4423 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4424 } catch (NameNotFoundException e) {
4425 Slog.e(TAG, "Invalid package restoring data", e);
4426 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4427 "Package missing on device");
4428 executeNextState(RestoreState.RUNNING_QUEUE);
4429 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004430 }
4431
Christopher Tatee7287a02012-09-07 18:32:12 -07004432 if (packageInfo.applicationInfo.backupAgentName == null
4433 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4434 if (DEBUG) {
4435 Slog.i(TAG, "Data exists for package " + packageName
4436 + " but app has no agent; skipping");
4437 }
4438 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4439 "Package has no agent");
4440 executeNextState(RestoreState.RUNNING_QUEUE);
4441 return;
4442 }
4443
Christopher Tate2982d062011-09-06 20:35:24 -07004444 if (metaInfo.versionCode > packageInfo.versionCode) {
4445 // Data is from a "newer" version of the app than we have currently
4446 // installed. If the app has not declared that it is prepared to
4447 // handle this case, we do not attempt the restore.
4448 if ((packageInfo.applicationInfo.flags
4449 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4450 String message = "Version " + metaInfo.versionCode
4451 + " > installed version " + packageInfo.versionCode;
4452 Slog.w(TAG, "Package " + packageName + ": " + message);
4453 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4454 packageName, message);
4455 executeNextState(RestoreState.RUNNING_QUEUE);
4456 return;
4457 } else {
4458 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4459 + " > installed " + packageInfo.versionCode
4460 + " but restoreAnyVersion");
4461 }
4462 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004463
Christopher Tate2982d062011-09-06 20:35:24 -07004464 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4465 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4466 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4467 "Signature mismatch");
4468 executeNextState(RestoreState.RUNNING_QUEUE);
4469 return;
4470 }
4471
4472 if (DEBUG) Slog.v(TAG, "Package " + packageName
4473 + " restore version [" + metaInfo.versionCode
4474 + "] is compatible with installed version ["
4475 + packageInfo.versionCode + "]");
4476
4477 // Then set up and bind the agent
4478 IBackupAgent agent = bindToAgentSynchronous(
4479 packageInfo.applicationInfo,
4480 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4481 if (agent == null) {
4482 Slog.w(TAG, "Can't find backup agent for " + packageName);
4483 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4484 "Restore agent missing");
4485 executeNextState(RestoreState.RUNNING_QUEUE);
4486 return;
4487 }
4488
4489 // And then finally start the restore on this agent
4490 try {
4491 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4492 ++mCount;
4493 } catch (Exception e) {
4494 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4495 agentErrorCleanup();
4496 executeNextState(RestoreState.RUNNING_QUEUE);
4497 }
4498 } catch (RemoteException e) {
4499 Slog.e(TAG, "Unable to fetch restore data from transport");
4500 mStatus = BackupConstants.TRANSPORT_ERROR;
4501 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004502 }
4503 }
4504
Christopher Tate2982d062011-09-06 20:35:24 -07004505 void finalizeRestore() {
4506 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4507
4508 try {
4509 mTransport.finishRestore();
4510 } catch (RemoteException e) {
4511 Slog.e(TAG, "Error finishing restore", e);
4512 }
4513
4514 if (mObserver != null) {
4515 try {
4516 mObserver.restoreFinished(mStatus);
4517 } catch (RemoteException e) {
4518 Slog.d(TAG, "Restore observer died at restoreFinished");
4519 }
4520 }
4521
4522 // If this was a restoreAll operation, record that this was our
4523 // ancestral dataset, as well as the set of apps that are possibly
4524 // restoreable from the dataset
4525 if (mTargetPackage == null && mPmAgent != null) {
4526 mAncestralPackages = mPmAgent.getRestoredPackages();
4527 mAncestralToken = mToken;
4528 writeRestoreTokens();
4529 }
4530
4531 // We must under all circumstances tell the Package Manager to
4532 // proceed with install notifications if it's waiting for us.
4533 if (mPmToken > 0) {
4534 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4535 try {
4536 mPackageManagerBinder.finishPackageInstall(mPmToken);
4537 } catch (RemoteException e) { /* can't happen */ }
4538 }
4539
4540 // Furthermore we need to reset the session timeout clock
4541 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4542 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4543 TIMEOUT_RESTORE_INTERVAL);
4544
4545 // done; we can finally release the wakelock
4546 Slog.i(TAG, "Restore complete.");
4547 mWakelock.release();
4548 }
4549
4550 // Call asynchronously into the app, passing it the restore data. The next step
4551 // after this is always a callback, either operationComplete() or handleTimeout().
4552 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004553 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004554 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004555 final String packageName = app.packageName;
4556
Christopher Tate2982d062011-09-06 20:35:24 -07004557 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004558
Christopher Tatec7b31e32009-06-10 15:49:30 -07004559 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004560 mBackupDataName = new File(mDataDir, packageName + ".restore");
4561 mNewStateName = new File(mStateDir, packageName + ".new");
4562 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004563
Christopher Tate4a627c72011-04-01 14:43:32 -07004564 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004565 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004566 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004567 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004568 ParcelFileDescriptor.MODE_READ_WRITE |
4569 ParcelFileDescriptor.MODE_CREATE |
4570 ParcelFileDescriptor.MODE_TRUNCATE);
4571
Christopher Tate2982d062011-09-06 20:35:24 -07004572 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004573 // Transport-level failure, so we wind everything up and
4574 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004575 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004576 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004577 mBackupData.close();
4578 mBackupDataName.delete();
4579 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004580 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004581 }
4582
4583 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004584 mBackupData.close();
4585 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004586 ParcelFileDescriptor.MODE_READ_ONLY);
4587
Christopher Tate2982d062011-09-06 20:35:24 -07004588 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004589 ParcelFileDescriptor.MODE_READ_WRITE |
4590 ParcelFileDescriptor.MODE_CREATE |
4591 ParcelFileDescriptor.MODE_TRUNCATE);
4592
Christopher Tate44a27902010-01-27 17:15:49 -08004593 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004594 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4595 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004596 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004597 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004598 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004599 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004600
Christopher Tate2982d062011-09-06 20:35:24 -07004601 // After a restore failure we go back to running the queue. If there
4602 // are no more packages to be restored that will be handled by the
4603 // next step.
4604 executeNextState(RestoreState.RUNNING_QUEUE);
4605 }
4606 }
Chris Tate249345b2010-10-29 12:57:04 -07004607
Christopher Tate2982d062011-09-06 20:35:24 -07004608 void agentErrorCleanup() {
4609 // If the agent fails restore, it might have put the app's data
4610 // into an incoherent state. For consistency we wipe its data
4611 // again in this case before continuing with normal teardown
4612 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4613 agentCleanup();
4614 }
4615
4616 void agentCleanup() {
4617 mBackupDataName.delete();
4618 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4619 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4620 mBackupData = mNewState = null;
4621
4622 // if everything went okay, remember the recorded state now
4623 //
4624 // !!! TODO: the restored data should be migrated on the server
4625 // side into the current dataset. In that case the new state file
4626 // we just created would reflect the data already extant in the
4627 // backend, so there'd be nothing more to do. Until that happens,
4628 // however, we need to make sure that we record the data to the
4629 // current backend dataset. (Yes, this means shipping the data over
4630 // the wire in both directions. That's bad, but consistency comes
4631 // first, then efficiency.) Once we introduce server-side data
4632 // migration to the newly-restored device's dataset, we will change
4633 // the following from a discard of the newly-written state to the
4634 // "correct" operation of renaming into the canonical state blob.
4635 mNewStateName.delete(); // TODO: remove; see above comment
4636 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4637
4638 // If this wasn't the PM pseudopackage, tear down the agent side
4639 if (mCurrentPackage.applicationInfo != null) {
4640 // unbind and tidy up even on timeout or failure
4641 try {
4642 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4643
4644 // The agent was probably running with a stub Application object,
4645 // which isn't a valid run mode for the main app logic. Shut
4646 // down the app so that next time it's launched, it gets the
4647 // usual full initialization. Note that this is only done for
4648 // full-system restores: when a single app has requested a restore,
4649 // it is explicitly not killed following that operation.
4650 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4651 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4652 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4653 + mCurrentPackage.applicationInfo.processName);
4654 mActivityManager.killApplicationProcess(
4655 mCurrentPackage.applicationInfo.processName,
4656 mCurrentPackage.applicationInfo.uid);
4657 }
4658 } catch (RemoteException e) {
4659 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004660 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004661 }
Christopher Tate2982d062011-09-06 20:35:24 -07004662
4663 // The caller is responsible for reestablishing the state machine; our
4664 // responsibility here is to clear the decks for whatever comes next.
4665 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4666 synchronized (mCurrentOpLock) {
4667 mCurrentOperations.clear();
4668 }
4669 }
4670
4671 // A call to agent.doRestore() has been positively acknowledged as complete
4672 @Override
4673 public void operationComplete() {
4674 int size = (int) mBackupDataName.length();
4675 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4676 // Just go back to running the restore queue
4677 agentCleanup();
4678
4679 executeNextState(RestoreState.RUNNING_QUEUE);
4680 }
4681
4682 // A call to agent.doRestore() has timed out
4683 @Override
4684 public void handleTimeout() {
4685 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4686 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4687 mCurrentPackage.packageName, "restore timeout");
4688 // Handle like an agent that threw on invocation: wipe it and go on to the next
4689 agentErrorCleanup();
4690 executeNextState(RestoreState.RUNNING_QUEUE);
4691 }
4692
4693 void executeNextState(RestoreState nextState) {
4694 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4695 + this + " nextState=" + nextState);
4696 mCurrentState = nextState;
4697 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4698 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004699 }
4700 }
4701
Christopher Tate44a27902010-01-27 17:15:49 -08004702 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004703 IBackupTransport mTransport;
4704 PackageInfo mPackage;
4705
Christopher Tate44a27902010-01-27 17:15:49 -08004706 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004707 mTransport = transport;
4708 mPackage = packageInfo;
4709 }
4710
Christopher Tateee0e78a2009-07-02 11:17:03 -07004711 public void run() {
4712 try {
4713 // Clear the on-device backup state to ensure a full backup next time
4714 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4715 File stateFile = new File(stateDir, mPackage.packageName);
4716 stateFile.delete();
4717
4718 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004719 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004720 mTransport.clearBackupData(mPackage);
4721 } catch (RemoteException e) {
4722 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004723 } catch (Exception e) {
4724 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004725 } finally {
4726 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004727 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004728 mTransport.finishBackup();
4729 } catch (RemoteException e) {
4730 // can't happen; the transport is local
4731 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004732
4733 // Last but not least, release the cpu
4734 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004735 }
4736 }
4737 }
4738
Christopher Tate44a27902010-01-27 17:15:49 -08004739 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004740 HashSet<String> mQueue;
4741
Christopher Tate44a27902010-01-27 17:15:49 -08004742 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004743 mQueue = transportNames;
4744 }
4745
Christopher Tate4cc86e12009-09-21 19:36:51 -07004746 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004747 try {
4748 for (String transportName : mQueue) {
4749 IBackupTransport transport = getTransport(transportName);
4750 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004751 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004752 continue;
4753 }
4754
Joe Onorato8a9b2202010-02-26 18:56:32 -08004755 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004756 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004757 long startRealtime = SystemClock.elapsedRealtime();
4758 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004759
Christopher Tate4cc86e12009-09-21 19:36:51 -07004760 if (status == BackupConstants.TRANSPORT_OK) {
4761 status = transport.finishBackup();
4762 }
4763
4764 // Okay, the wipe really happened. Clean up our local bookkeeping.
4765 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004766 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004767 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004768 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004769 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004770 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004771 synchronized (mQueueLock) {
4772 recordInitPendingLocked(false, transportName);
4773 }
Dan Egnor726247c2009-09-29 19:12:31 -07004774 } else {
4775 // If this didn't work, requeue this one and try again
4776 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004777 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004778 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004779 synchronized (mQueueLock) {
4780 recordInitPendingLocked(true, transportName);
4781 }
4782 // do this via another alarm to make sure of the wakelock states
4783 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004784 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004785 + transportName + " resched in " + delay);
4786 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4787 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004788 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004789 }
4790 } catch (RemoteException e) {
4791 // can't happen; the transports are local
4792 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004793 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004794 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004795 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004796 mWakelock.release();
4797 }
4798 }
4799 }
4800
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004801 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004802 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004803 dataChangedImpl(packageName, targets);
4804 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004805
Christopher Tatea3d55342012-03-27 13:16:18 -07004806 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004807 // Record that we need a backup pass for the caller. Since multiple callers
4808 // may share a uid, we need to note all candidates within that uid and schedule
4809 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004810 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004811
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004812 if (targets == null) {
4813 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4814 + " uid=" + Binder.getCallingUid());
4815 return;
4816 }
4817
4818 synchronized (mQueueLock) {
4819 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004820 if (targets.contains(packageName)) {
4821 // Add the caller to the set of pending backups. If there is
4822 // one already there, then overwrite it, but no harm done.
4823 BackupRequest req = new BackupRequest(packageName);
4824 if (mPendingBackups.put(packageName, req) == null) {
4825 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004826
Christopher Tatea3d55342012-03-27 13:16:18 -07004827 // Journal this request in case of crash. The put()
4828 // operation returned null when this package was not already
4829 // in the set; we want to avoid touching the disk redundantly.
4830 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004831
Christopher Tatea3d55342012-03-27 13:16:18 -07004832 if (MORE_DEBUG) {
4833 int numKeys = mPendingBackups.size();
4834 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4835 for (BackupRequest b : mPendingBackups.values()) {
4836 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004837 }
4838 }
4839 }
4840 }
4841 }
4842 }
4843
4844 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004845 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004846 // If the caller does not hold the BACKUP permission, it can only request a
4847 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004848 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004849 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004850 synchronized (mBackupParticipants) {
4851 return mBackupParticipants.get(Binder.getCallingUid());
4852 }
4853 }
4854
4855 // a caller with full permission can ask to back up any participating app
4856 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004857 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004858 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004859 int N = mBackupParticipants.size();
4860 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004861 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004862 if (s != null) {
4863 targets.addAll(s);
4864 }
4865 }
4866 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004867 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004868 }
Christopher Tate46758122009-05-06 11:22:00 -07004869
Christopher Tatecde87f42009-06-12 12:55:53 -07004870 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004871 RandomAccessFile out = null;
4872 try {
4873 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4874 out = new RandomAccessFile(mJournal, "rws");
4875 out.seek(out.length());
4876 out.writeUTF(str);
4877 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004878 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004879 mJournal = null;
4880 } finally {
4881 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004882 }
4883 }
4884
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004885 // ----- IBackupManager binder interface -----
4886
4887 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004888 final int callingUserHandle = UserHandle.getCallingUserId();
4889 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004890 // App is running under a non-owner user profile. For now, we do not back
4891 // up data from secondary user profiles.
4892 // TODO: backups for all user profiles.
4893 if (MORE_DEBUG) {
4894 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4895 + callingUserHandle);
4896 }
4897 return;
4898 }
4899
Christopher Tatea3d55342012-03-27 13:16:18 -07004900 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004901 if (targets == null) {
4902 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4903 + " uid=" + Binder.getCallingUid());
4904 return;
4905 }
4906
4907 mBackupHandler.post(new Runnable() {
4908 public void run() {
4909 dataChangedImpl(packageName, targets);
4910 }
4911 });
4912 }
4913
Christopher Tateee0e78a2009-07-02 11:17:03 -07004914 // Clear the given package's backup data from the current transport
4915 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004916 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004917 PackageInfo info;
4918 try {
4919 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4920 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004921 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004922 return;
4923 }
4924
4925 // If the caller does not hold the BACKUP permission, it can only request a
4926 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004927 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004928 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004929 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4930 apps = mBackupParticipants.get(Binder.getCallingUid());
4931 } else {
4932 // a caller with full permission can ask to back up any participating app
4933 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004934 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004935 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004936 int N = mBackupParticipants.size();
4937 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004938 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004939 if (s != null) {
4940 apps.addAll(s);
4941 }
4942 }
4943 }
4944
Christopher Tatea3d55342012-03-27 13:16:18 -07004945 // Is the given app an available participant?
4946 if (apps.contains(packageName)) {
4947 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4948 // found it; fire off the clear request
4949 synchronized (mQueueLock) {
4950 long oldId = Binder.clearCallingIdentity();
4951 mWakelock.acquire();
4952 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4953 new ClearParams(getTransport(mCurrentTransport), info));
4954 mBackupHandler.sendMessage(msg);
4955 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004956 }
4957 }
4958 }
4959
Christopher Tateace7f092009-06-15 18:07:25 -07004960 // Run a backup pass immediately for any applications that have declared
4961 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004962 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004964
Joe Onorato8a9b2202010-02-26 18:56:32 -08004965 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004966 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004967 // Because the alarms we are using can jitter, and we want an *immediate*
4968 // backup pass to happen, we restart the timer beginning with "next time,"
4969 // then manually fire the backup trigger intent ourselves.
4970 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004971 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004972 mRunBackupIntent.send();
4973 } catch (PendingIntent.CanceledException e) {
4974 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004975 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004976 }
Christopher Tate46758122009-05-06 11:22:00 -07004977 }
4978 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004979
Christopher Tated2c0cd42011-09-15 15:51:29 -07004980 boolean deviceIsProvisioned() {
4981 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07004982 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004983 }
4984
Christopher Tate4a627c72011-04-01 14:43:32 -07004985 // Run a *full* backup pass for the given package, writing the resulting data stream
4986 // to the supplied file descriptor. This method is synchronous and does not return
4987 // to the caller until the backup has been completed.
4988 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004989 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004990 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4991
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004992 final int callingUserHandle = UserHandle.getCallingUserId();
4993 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004994 throw new IllegalStateException("Backup supported only for the device owner");
4995 }
4996
Christopher Tate4a627c72011-04-01 14:43:32 -07004997 // Validate
4998 if (!doAllApps) {
4999 if (!includeShared) {
5000 // If we're backing up shared data (sdcard or equivalent), then we can run
5001 // without any supplied app names. Otherwise, we'd be doing no work, so
5002 // report the error.
5003 if (pkgList == null || pkgList.length == 0) {
5004 throw new IllegalArgumentException(
5005 "Backup requested but neither shared nor any apps named");
5006 }
5007 }
5008 }
5009
Christopher Tate4a627c72011-04-01 14:43:32 -07005010 long oldId = Binder.clearCallingIdentity();
5011 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005012 // Doesn't make sense to do a full backup prior to setup
5013 if (!deviceIsProvisioned()) {
5014 Slog.i(TAG, "Full backup not supported before setup");
5015 return;
5016 }
5017
5018 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5019 + " shared=" + includeShared + " all=" + doAllApps
5020 + " pkgs=" + pkgList);
5021 Slog.i(TAG, "Beginning full backup...");
5022
Christopher Tate4a627c72011-04-01 14:43:32 -07005023 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005024 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005025 final int token = generateToken();
5026 synchronized (mFullConfirmations) {
5027 mFullConfirmations.put(token, params);
5028 }
5029
Christopher Tate75a99702011-05-18 16:28:19 -07005030 // start up the confirmation UI
5031 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5032 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5033 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005034 mFullConfirmations.delete(token);
5035 return;
5036 }
Christopher Tate75a99702011-05-18 16:28:19 -07005037
5038 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005039 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5040
5041 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005042 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005043
5044 // wait for the backup to be performed
5045 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5046 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005047 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005048 try {
5049 fd.close();
5050 } catch (IOException e) {
5051 // just eat it
5052 }
Christopher Tate75a99702011-05-18 16:28:19 -07005053 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005054 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005055 }
Christopher Tate75a99702011-05-18 16:28:19 -07005056 }
5057
5058 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005059 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005060
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005061 final int callingUserHandle = UserHandle.getCallingUserId();
5062 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005063 throw new IllegalStateException("Restore supported only for the device owner");
5064 }
5065
Christopher Tate75a99702011-05-18 16:28:19 -07005066 long oldId = Binder.clearCallingIdentity();
5067
5068 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005069 // Check whether the device has been provisioned -- we don't handle
5070 // full restores prior to completing the setup process.
5071 if (!deviceIsProvisioned()) {
5072 Slog.i(TAG, "Full restore not permitted before setup");
5073 return;
5074 }
5075
5076 Slog.i(TAG, "Beginning full restore...");
5077
Christopher Tate75a99702011-05-18 16:28:19 -07005078 FullRestoreParams params = new FullRestoreParams(fd);
5079 final int token = generateToken();
5080 synchronized (mFullConfirmations) {
5081 mFullConfirmations.put(token, params);
5082 }
5083
5084 // start up the confirmation UI
5085 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5086 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5087 Slog.e(TAG, "Unable to launch full restore confirmation");
5088 mFullConfirmations.delete(token);
5089 return;
5090 }
5091
5092 // make sure the screen is lit for the user interaction
5093 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5094
5095 // start the confirmation countdown
5096 startConfirmationTimeout(token, params);
5097
5098 // wait for the restore to be performed
5099 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5100 waitForCompletion(params);
5101 } finally {
5102 try {
5103 fd.close();
5104 } catch (IOException e) {
5105 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5106 }
5107 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005108 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005109 }
5110 }
5111
5112 boolean startConfirmationUi(int token, String action) {
5113 try {
5114 Intent confIntent = new Intent(action);
5115 confIntent.setClassName("com.android.backupconfirm",
5116 "com.android.backupconfirm.BackupRestoreConfirmation");
5117 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5118 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5119 mContext.startActivity(confIntent);
5120 } catch (ActivityNotFoundException e) {
5121 return false;
5122 }
5123 return true;
5124 }
5125
5126 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005127 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005128 + TIMEOUT_FULL_CONFIRMATION + " millis");
5129 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5130 token, 0, params);
5131 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005132 }
5133
5134 void waitForCompletion(FullParams params) {
5135 synchronized (params.latch) {
5136 while (params.latch.get() == false) {
5137 try {
5138 params.latch.wait();
5139 } catch (InterruptedException e) { /* never interrupted */ }
5140 }
5141 }
5142 }
5143
5144 void signalFullBackupRestoreCompletion(FullParams params) {
5145 synchronized (params.latch) {
5146 params.latch.set(true);
5147 params.latch.notifyAll();
5148 }
5149 }
5150
5151 // Confirm that the previously-requested full backup/restore operation can proceed. This
5152 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005153 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005154 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005155 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005156 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5157 + " allow=" + allow);
5158
5159 // TODO: possibly require not just this signature-only permission, but even
5160 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005161 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005162
5163 long oldId = Binder.clearCallingIdentity();
5164 try {
5165
5166 FullParams params;
5167 synchronized (mFullConfirmations) {
5168 params = mFullConfirmations.get(token);
5169 if (params != null) {
5170 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5171 mFullConfirmations.delete(token);
5172
5173 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005174 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005175 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005176 : MSG_RUN_FULL_RESTORE;
5177
Christopher Tate728a1c42011-07-28 18:03:03 -07005178 params.observer = observer;
5179 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005180
5181 boolean isEncrypted;
5182 try {
5183 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5184 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5185 } catch (RemoteException e) {
5186 // couldn't contact the mount service; fail "safe" and assume encryption
5187 Slog.e(TAG, "Unable to contact mount service!");
5188 isEncrypted = true;
5189 }
5190 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005191
Christopher Tate75a99702011-05-18 16:28:19 -07005192 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005193 mWakelock.acquire();
5194 Message msg = mBackupHandler.obtainMessage(verb, params);
5195 mBackupHandler.sendMessage(msg);
5196 } else {
5197 Slog.w(TAG, "User rejected full backup/restore operation");
5198 // indicate completion without having actually transferred any data
5199 signalFullBackupRestoreCompletion(params);
5200 }
5201 } else {
5202 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5203 }
5204 }
5205 } finally {
5206 Binder.restoreCallingIdentity(oldId);
5207 }
5208 }
5209
Christopher Tate8031a3d2009-07-06 16:36:05 -07005210 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005211 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005213 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005214
Joe Onorato8a9b2202010-02-26 18:56:32 -08005215 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005216
Christopher Tate6ef58a12009-06-29 14:56:28 -07005217 boolean wasEnabled = mEnabled;
5218 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005219 Settings.Secure.putInt(mContext.getContentResolver(),
5220 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005221 mEnabled = enable;
5222 }
5223
Christopher Tate49401dd2009-07-01 12:34:29 -07005224 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005225 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005226 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005227 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005228 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005229 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005230 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005231
Christopher Tateb6787f22009-07-02 17:40:45 -07005232 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005233
5234 // This also constitutes an opt-out, so we wipe any data for
5235 // this device from the backend. We start that process with
5236 // an alarm in order to guarantee wakelock states.
5237 if (wasEnabled && mProvisioned) {
5238 // NOTE: we currently flush every registered transport, not just
5239 // the currently-active one.
5240 HashSet<String> allTransports;
5241 synchronized (mTransports) {
5242 allTransports = new HashSet<String>(mTransports.keySet());
5243 }
5244 // build the set of transports for which we are posting an init
5245 for (String transport : allTransports) {
5246 recordInitPendingLocked(true, transport);
5247 }
5248 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5249 mRunInitIntent);
5250 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005251 }
5252 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005253 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005254
Christopher Tatecce9da52010-02-03 15:11:15 -08005255 // Enable/disable automatic restore of app data at install time
5256 public void setAutoRestore(boolean doAutoRestore) {
5257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005258 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005259
Joe Onorato8a9b2202010-02-26 18:56:32 -08005260 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005261
5262 synchronized (this) {
5263 Settings.Secure.putInt(mContext.getContentResolver(),
5264 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5265 mAutoRestore = doAutoRestore;
5266 }
5267 }
5268
Christopher Tate8031a3d2009-07-06 16:36:05 -07005269 // Mark the backup service as having been provisioned
5270 public void setBackupProvisioned(boolean available) {
5271 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5272 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005273 /*
5274 * This is now a no-op; provisioning is simply the device's own setup state.
5275 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005276 }
5277
5278 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005279 // We used to use setInexactRepeating(), but that may be linked to
5280 // backups running at :00 more often than not, creating load spikes.
5281 // Schedule at an exact time for now, and also add a bit of "fuzz".
5282
5283 Random random = new Random();
5284 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5285 random.nextInt(FUZZ_MILLIS);
5286 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5287 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005288 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005289 }
5290
Christopher Tate6ef58a12009-06-29 14:56:28 -07005291 // Report whether the backup mechanism is currently enabled
5292 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005294 return mEnabled; // no need to synchronize just to read it
5295 }
5296
Christopher Tate91717492009-06-26 21:07:13 -07005297 // Report the name of the currently active transport
5298 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005299 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005300 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005301 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005302 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005303 }
5304
Christopher Tate91717492009-06-26 21:07:13 -07005305 // Report all known, available backup transports
5306 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005308
Christopher Tate91717492009-06-26 21:07:13 -07005309 String[] list = null;
5310 ArrayList<String> known = new ArrayList<String>();
5311 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5312 if (entry.getValue() != null) {
5313 known.add(entry.getKey());
5314 }
5315 }
5316
5317 if (known.size() > 0) {
5318 list = new String[known.size()];
5319 known.toArray(list);
5320 }
5321 return list;
5322 }
5323
5324 // Select which transport to use for the next backup operation. If the given
5325 // name is not one of the available transports, no action is taken and the method
5326 // returns null.
5327 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005329
5330 synchronized (mTransports) {
5331 String prevTransport = null;
5332 if (mTransports.get(transport) != null) {
5333 prevTransport = mCurrentTransport;
5334 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005335 Settings.Secure.putString(mContext.getContentResolver(),
5336 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005337 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005338 + " returning " + prevTransport);
5339 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005340 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005341 }
5342 return prevTransport;
5343 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005344 }
5345
Christopher Tatef5e1c292010-12-08 18:40:26 -08005346 // Supply the configuration Intent for the given transport. If the name is not one
5347 // of the available transports, or if the transport does not supply any configuration
5348 // UI, the method returns null.
5349 public Intent getConfigurationIntent(String transportName) {
5350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5351 "getConfigurationIntent");
5352
5353 synchronized (mTransports) {
5354 final IBackupTransport transport = mTransports.get(transportName);
5355 if (transport != null) {
5356 try {
5357 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005358 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005359 + intent);
5360 return intent;
5361 } catch (RemoteException e) {
5362 /* fall through to return null */
5363 }
5364 }
5365 }
5366
5367 return null;
5368 }
5369
5370 // Supply the configuration summary string for the given transport. If the name is
5371 // not one of the available transports, or if the transport does not supply any
5372 // summary / destination string, the method can return null.
5373 //
5374 // This string is used VERBATIM as the summary text of the relevant Settings item!
5375 public String getDestinationString(String transportName) {
5376 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005377 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005378
5379 synchronized (mTransports) {
5380 final IBackupTransport transport = mTransports.get(transportName);
5381 if (transport != null) {
5382 try {
5383 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005384 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005385 return text;
5386 } catch (RemoteException e) {
5387 /* fall through to return null */
5388 }
5389 }
5390 }
5391
5392 return null;
5393 }
5394
Christopher Tate043dadc2009-06-02 16:11:00 -07005395 // Callback: a requested backup agent has been instantiated. This should only
5396 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005397 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005398 synchronized(mAgentConnectLock) {
5399 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005401 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5402 mConnectedAgent = agent;
5403 mConnecting = false;
5404 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005405 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005406 + " claiming agent connected");
5407 }
5408 mAgentConnectLock.notifyAll();
5409 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005410 }
5411
5412 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5413 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005414 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005415 public void agentDisconnected(String packageName) {
5416 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005417 synchronized(mAgentConnectLock) {
5418 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5419 mConnectedAgent = null;
5420 mConnecting = false;
5421 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005422 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005423 + " claiming agent disconnected");
5424 }
5425 mAgentConnectLock.notifyAll();
5426 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005427 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005428
Christopher Tate1bb69062010-02-19 17:02:12 -08005429 // An application being installed will need a restore pass, then the Package Manager
5430 // will need to be told when the restore is finished.
5431 public void restoreAtInstall(String packageName, int token) {
5432 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005433 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005434 + " attemping install-time restore");
5435 return;
5436 }
5437
5438 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005439 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005440 + " token=" + Integer.toHexString(token));
5441
Christopher Tatef0872722010-02-25 15:22:48 -08005442 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005443 // okay, we're going to attempt a restore of this package from this restore set.
5444 // The eventual message back into the Package Manager to run the post-install
5445 // steps for 'token' will be issued from the restore handling code.
5446
5447 // We can use a synthetic PackageInfo here because:
5448 // 1. We know it's valid, since the Package Manager supplied the name
5449 // 2. Only the packageName field will be used by the restore code
5450 PackageInfo pkg = new PackageInfo();
5451 pkg.packageName = packageName;
5452
5453 mWakelock.acquire();
5454 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5455 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005456 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005457 mBackupHandler.sendMessage(msg);
5458 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005459 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5460 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005461 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005462 try {
5463 mPackageManagerBinder.finishPackageInstall(token);
5464 } catch (RemoteException e) { /* can't happen */ }
5465 }
5466 }
5467
Christopher Tate8c850b72009-06-07 19:33:20 -07005468 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005469 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5470 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5471 + " transport=" + transport);
5472
5473 boolean needPermission = true;
5474 if (transport == null) {
5475 transport = mCurrentTransport;
5476
5477 if (packageName != null) {
5478 PackageInfo app = null;
5479 try {
5480 app = mPackageManager.getPackageInfo(packageName, 0);
5481 } catch (NameNotFoundException nnf) {
5482 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5483 throw new IllegalArgumentException("Package " + packageName + " not found");
5484 }
5485
5486 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5487 // So: using the current active transport, and the caller has asked
5488 // that its own package will be restored. In this narrow use case
5489 // we do not require the caller to hold the permission.
5490 needPermission = false;
5491 }
5492 }
5493 }
5494
5495 if (needPermission) {
5496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5497 "beginRestoreSession");
5498 } else {
5499 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5500 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005501
5502 synchronized(this) {
5503 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005504 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005505 return null;
5506 }
Chris Tate44ab8452010-11-16 15:10:49 -08005507 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005508 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005509 }
5510 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005511 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005512
Christopher Tate73a3cb32010-12-13 18:27:26 -08005513 void clearRestoreSession(ActiveRestoreSession currentSession) {
5514 synchronized(this) {
5515 if (currentSession != mActiveRestoreSession) {
5516 Slog.e(TAG, "ending non-current restore session");
5517 } else {
5518 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5519 mActiveRestoreSession = null;
5520 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5521 }
5522 }
5523 }
5524
Christopher Tate44a27902010-01-27 17:15:49 -08005525 // Note that a currently-active backup agent has notified us that it has
5526 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005527 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005528 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005529 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5530 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005531 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005532 op = mCurrentOperations.get(token);
5533 if (op != null) {
5534 op.state = OP_ACKNOWLEDGED;
5535 }
Christopher Tate44a27902010-01-27 17:15:49 -08005536 mCurrentOpLock.notifyAll();
5537 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005538
5539 // The completion callback, if any, is invoked on the handler
5540 if (op != null && op.callback != null) {
5541 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5542 mBackupHandler.sendMessage(msg);
5543 }
Christopher Tate44a27902010-01-27 17:15:49 -08005544 }
5545
Christopher Tate9b3905c2009-06-08 15:24:01 -07005546 // ----- Restore session -----
5547
Christopher Tate80202c82010-01-25 19:37:47 -08005548 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005549 private static final String TAG = "RestoreSession";
5550
Chris Tate44ab8452010-11-16 15:10:49 -08005551 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005552 private IBackupTransport mRestoreTransport = null;
5553 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005554 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005555
Chris Tate44ab8452010-11-16 15:10:49 -08005556 ActiveRestoreSession(String packageName, String transport) {
5557 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005558 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005559 }
5560
5561 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005562 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005564 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005565 if (observer == null) {
5566 throw new IllegalArgumentException("Observer must not be null");
5567 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005568
Christopher Tate73a3cb32010-12-13 18:27:26 -08005569 if (mEnded) {
5570 throw new IllegalStateException("Restore session already ended");
5571 }
5572
Christopher Tate1bb69062010-02-19 17:02:12 -08005573 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005574 try {
Christopher Tate43383042009-07-13 15:17:13 -07005575 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005576 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005577 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005578 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005579 // spin off the transport request to our service thread
5580 mWakelock.acquire();
5581 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5582 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5583 mBackupHandler.sendMessage(msg);
5584 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005585 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005586 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005587 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005588 } finally {
5589 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005590 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005591 }
5592
Christopher Tate84725812010-02-04 15:52:40 -08005593 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005594 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5595 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005596
Chris Tate44ab8452010-11-16 15:10:49 -08005597 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005598 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005599
Christopher Tate73a3cb32010-12-13 18:27:26 -08005600 if (mEnded) {
5601 throw new IllegalStateException("Restore session already ended");
5602 }
5603
Dan Egnor0084da52009-07-29 12:57:16 -07005604 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005605 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5606 return -1;
5607 }
5608
5609 if (mPackageName != null) {
5610 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005611 return -1;
5612 }
5613
Christopher Tate21ab6a52009-09-24 18:01:46 -07005614 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005615 for (int i = 0; i < mRestoreSets.length; i++) {
5616 if (token == mRestoreSets[i].token) {
5617 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005618 mWakelock.acquire();
5619 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005620 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005621 mBackupHandler.sendMessage(msg);
5622 Binder.restoreCallingIdentity(oldId);
5623 return 0;
5624 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005625 }
5626 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005627
Joe Onorato8a9b2202010-02-26 18:56:32 -08005628 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005629 return -1;
5630 }
5631
Christopher Tate284f1bb2011-07-07 14:31:18 -07005632 public synchronized int restoreSome(long token, IRestoreObserver observer,
5633 String[] packages) {
5634 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5635 "performRestore");
5636
5637 if (DEBUG) {
5638 StringBuilder b = new StringBuilder(128);
5639 b.append("restoreSome token=");
5640 b.append(Long.toHexString(token));
5641 b.append(" observer=");
5642 b.append(observer.toString());
5643 b.append(" packages=");
5644 if (packages == null) {
5645 b.append("null");
5646 } else {
5647 b.append('{');
5648 boolean first = true;
5649 for (String s : packages) {
5650 if (!first) {
5651 b.append(", ");
5652 } else first = false;
5653 b.append(s);
5654 }
5655 b.append('}');
5656 }
5657 Slog.d(TAG, b.toString());
5658 }
5659
5660 if (mEnded) {
5661 throw new IllegalStateException("Restore session already ended");
5662 }
5663
5664 if (mRestoreTransport == null || mRestoreSets == null) {
5665 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5666 return -1;
5667 }
5668
5669 if (mPackageName != null) {
5670 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5671 return -1;
5672 }
5673
5674 synchronized (mQueueLock) {
5675 for (int i = 0; i < mRestoreSets.length; i++) {
5676 if (token == mRestoreSets[i].token) {
5677 long oldId = Binder.clearCallingIdentity();
5678 mWakelock.acquire();
5679 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5680 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5681 packages, true);
5682 mBackupHandler.sendMessage(msg);
5683 Binder.restoreCallingIdentity(oldId);
5684 return 0;
5685 }
5686 }
5687 }
5688
5689 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5690 return -1;
5691 }
5692
Christopher Tate84725812010-02-04 15:52:40 -08005693 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005694 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005695
Christopher Tate73a3cb32010-12-13 18:27:26 -08005696 if (mEnded) {
5697 throw new IllegalStateException("Restore session already ended");
5698 }
5699
Chris Tate44ab8452010-11-16 15:10:49 -08005700 if (mPackageName != null) {
5701 if (! mPackageName.equals(packageName)) {
5702 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5703 + " on session for package " + mPackageName);
5704 return -1;
5705 }
5706 }
5707
Christopher Tate84725812010-02-04 15:52:40 -08005708 PackageInfo app = null;
5709 try {
5710 app = mPackageManager.getPackageInfo(packageName, 0);
5711 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005712 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005713 return -1;
5714 }
5715
5716 // If the caller is not privileged and is not coming from the target
5717 // app's uid, throw a permission exception back to the caller.
5718 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5719 Binder.getCallingPid(), Binder.getCallingUid());
5720 if ((perm == PackageManager.PERMISSION_DENIED) &&
5721 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005722 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005723 + " or calling uid=" + Binder.getCallingUid());
5724 throw new SecurityException("No permission to restore other packages");
5725 }
5726
Christopher Tate7d411a32010-02-26 11:27:08 -08005727 // If the package has no backup agent, we obviously cannot proceed
5728 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005729 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005730 return -1;
5731 }
5732
Christopher Tate84725812010-02-04 15:52:40 -08005733 // So far so good; we're allowed to try to restore this package. Now
5734 // check whether there is data for it in the current dataset, falling back
5735 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005736 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005737
5738 // If we didn't come up with a place to look -- no ancestral dataset and
5739 // the app has never been backed up from this device -- there's nothing
5740 // to do but return failure.
5741 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005742 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005743 return -1;
5744 }
5745
5746 // Ready to go: enqueue the restore request and claim success
5747 long oldId = Binder.clearCallingIdentity();
5748 mWakelock.acquire();
5749 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005750 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005751 mBackupHandler.sendMessage(msg);
5752 Binder.restoreCallingIdentity(oldId);
5753 return 0;
5754 }
5755
Christopher Tate73a3cb32010-12-13 18:27:26 -08005756 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5757 class EndRestoreRunnable implements Runnable {
5758 BackupManagerService mBackupManager;
5759 ActiveRestoreSession mSession;
5760
5761 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5762 mBackupManager = manager;
5763 mSession = session;
5764 }
5765
5766 public void run() {
5767 // clean up the session's bookkeeping
5768 synchronized (mSession) {
5769 try {
5770 if (mSession.mRestoreTransport != null) {
5771 mSession.mRestoreTransport.finishRestore();
5772 }
5773 } catch (Exception e) {
5774 Slog.e(TAG, "Error in finishRestore", e);
5775 } finally {
5776 mSession.mRestoreTransport = null;
5777 mSession.mEnded = true;
5778 }
5779 }
5780
5781 // clean up the BackupManagerService side of the bookkeeping
5782 // and cancel any pending timeout message
5783 mBackupManager.clearRestoreSession(mSession);
5784 }
5785 }
5786
Dan Egnor0084da52009-07-29 12:57:16 -07005787 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005788 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005789
Christopher Tate73a3cb32010-12-13 18:27:26 -08005790 if (mEnded) {
5791 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005792 }
5793
Christopher Tate73a3cb32010-12-13 18:27:26 -08005794 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005795 }
5796 }
5797
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005798 @Override
5799 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5801
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005802 long identityToken = Binder.clearCallingIdentity();
5803 try {
5804 dumpInternal(pw);
5805 } finally {
5806 Binder.restoreCallingIdentity(identityToken);
5807 }
5808 }
5809
5810 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005811 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005812 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005813 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005814 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005815 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005816 if (mBackupRunning) pw.println("Backup currently running");
5817 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005818 + " (now = " + System.currentTimeMillis() + ')');
5819 pw.println(" next scheduled: " + mNextBackupPass);
5820
Christopher Tate91717492009-06-26 21:07:13 -07005821 pw.println("Available transports:");
5822 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005823 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5824 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005825 IBackupTransport transport = getTransport(t);
5826 File dir = new File(mBaseStateDir, transport.transportDirName());
5827 pw.println(" destination: " + transport.currentDestinationString());
5828 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005829 for (File f : dir.listFiles()) {
5830 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5831 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005832 } catch (Exception e) {
5833 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005834 pw.println(" Error: " + e);
5835 }
Christopher Tate91717492009-06-26 21:07:13 -07005836 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005837
5838 pw.println("Pending init: " + mPendingInits.size());
5839 for (String s : mPendingInits) {
5840 pw.println(" " + s);
5841 }
5842
Christopher Tate6de74ff2012-01-17 15:20:32 -08005843 if (DEBUG_BACKUP_TRACE) {
5844 synchronized (mBackupTrace) {
5845 if (!mBackupTrace.isEmpty()) {
5846 pw.println("Most recent backup trace:");
5847 for (String s : mBackupTrace) {
5848 pw.println(" " + s);
5849 }
5850 }
5851 }
5852 }
5853
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005854 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005855 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005856 for (int i=0; i<N; i++) {
5857 int uid = mBackupParticipants.keyAt(i);
5858 pw.print(" uid: ");
5859 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005860 HashSet<String> participants = mBackupParticipants.valueAt(i);
5861 for (String app: participants) {
5862 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005863 }
5864 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005865
Christopher Tateb49ceb32010-02-08 16:22:24 -08005866 pw.println("Ancestral packages: "
5867 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005868 if (mAncestralPackages != null) {
5869 for (String pkg : mAncestralPackages) {
5870 pw.println(" " + pkg);
5871 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005872 }
5873
Christopher Tate73e02522009-07-15 14:18:26 -07005874 pw.println("Ever backed up: " + mEverStoredApps.size());
5875 for (String pkg : mEverStoredApps) {
5876 pw.println(" " + pkg);
5877 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005878
5879 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005880 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005881 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005882 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005883 }
5884 }
Christopher Tate487529a2009-04-29 14:03:25 -07005885}