blob: a6624193a69780d1b6d81590d9ede8720d2af960 [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
Christopher Tatee82f68d2012-10-23 15:07:38 -07001436 // Schedule a backup for it on general principles
1437 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1438 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001439 }
Christopher Tate487529a2009-04-29 14:03:25 -07001440 }
1441 }
1442
Christopher Tate0bacfd22012-01-11 14:41:19 -08001443 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001444 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001445 if (packageNames == null) {
1446 Slog.w(TAG, "removePackageParticipants with null list");
1447 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001448 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001449
Christopher Tatea3d55342012-03-27 13:16:18 -07001450 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1451 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001452 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001453 // Known previous UID, so we know which package set to check
1454 HashSet<String> set = mBackupParticipants.get(oldUid);
1455 if (set != null && set.contains(pkg)) {
1456 removePackageFromSetLocked(set, pkg);
1457 if (set.isEmpty()) {
1458 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1459 mBackupParticipants.remove(oldUid);
1460 }
1461 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001462 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001463 }
1464
Christopher Tatea3d55342012-03-27 13:16:18 -07001465 private void removePackageFromSetLocked(final HashSet<String> set,
1466 final String packageName) {
1467 if (set.contains(packageName)) {
1468 // Found it. Remove this one package from the bookkeeping, and
1469 // if it's the last participating app under this uid we drop the
1470 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001471 // Note that we deliberately leave it 'known' in the "ever backed up"
1472 // bookkeeping so that its current-dataset data will be retrieved
1473 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001474 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001475 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001476 mPendingBackups.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 Tate346acb12012-10-15 19:20:25 -07001628 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001629 return null;
1630 }
1631 }
1632
1633 // if we timed out with no connect, abort and move on
1634 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001635 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001636 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001637 return null;
1638 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001639 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001640 agent = mConnectedAgent;
1641 }
1642 } catch (RemoteException e) {
1643 // can't happen
1644 }
1645 }
1646 return agent;
1647 }
1648
Christopher Tatec7b31e32009-06-10 15:49:30 -07001649 // clear an application's data, blocking until the operation completes or times out
1650 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001651 // Don't wipe packages marked allowClearUserData=false
1652 try {
1653 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1654 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001655 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001656 + packageName);
1657 return;
1658 }
1659 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001660 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001661 return;
1662 }
1663
Christopher Tatec7b31e32009-06-10 15:49:30 -07001664 ClearDataObserver observer = new ClearDataObserver();
1665
1666 synchronized(mClearDataLock) {
1667 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001668 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001669 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001670 } catch (RemoteException e) {
1671 // can't happen because the activity manager is in this process
1672 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001673
1674 // only wait 10 seconds for the clear data to happen
1675 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1676 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1677 try {
1678 mClearDataLock.wait(5000);
1679 } catch (InterruptedException e) {
1680 // won't happen, but still.
1681 mClearingData = false;
1682 }
1683 }
1684 }
1685 }
1686
1687 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001688 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001689 synchronized(mClearDataLock) {
1690 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001691 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001692 }
1693 }
1694 }
1695
Christopher Tate1bb69062010-02-19 17:02:12 -08001696 // Get the restore-set token for the best-available restore set for this package:
1697 // the active set if possible, else the ancestral one. Returns zero if none available.
1698 long getAvailableRestoreToken(String packageName) {
1699 long token = mAncestralToken;
1700 synchronized (mQueueLock) {
1701 if (mEverStoredApps.contains(packageName)) {
1702 token = mCurrentToken;
1703 }
1704 }
1705 return token;
1706 }
1707
Christopher Tate44a27902010-01-27 17:15:49 -08001708 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001709 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1710
1711 interface BackupRestoreTask {
1712 // Execute one tick of whatever state machine the task implements
1713 void execute();
1714
1715 // An operation that wanted a callback has completed
1716 void operationComplete();
1717
1718 // An operation that wanted a callback has timed out
1719 void handleTimeout();
1720 }
1721
1722 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1723 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1724 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001725 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001726 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1727
1728 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1729 mBackupHandler.sendMessageDelayed(msg, interval);
1730 }
1731 }
1732
1733 // synchronous waiter case
1734 boolean waitUntilOperationComplete(int token) {
1735 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1736 + Integer.toHexString(token));
1737 int finalState = OP_PENDING;
1738 Operation op = null;
1739 synchronized (mCurrentOpLock) {
1740 while (true) {
1741 op = mCurrentOperations.get(token);
1742 if (op == null) {
1743 // mysterious disappearance: treat as success with no callback
1744 break;
1745 } else {
1746 if (op.state == OP_PENDING) {
1747 try {
1748 mCurrentOpLock.wait();
1749 } catch (InterruptedException e) {}
1750 // When the wait is notified we loop around and recheck the current state
1751 } else {
1752 // No longer pending; we're done
1753 finalState = op.state;
1754 break;
1755 }
Christopher Tate44a27902010-01-27 17:15:49 -08001756 }
Christopher Tate44a27902010-01-27 17:15:49 -08001757 }
1758 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001759
Christopher Tate44a27902010-01-27 17:15:49 -08001760 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001761 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001762 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001763 return finalState == OP_ACKNOWLEDGED;
1764 }
1765
Christopher Tate8e294d42011-08-31 20:37:12 -07001766 void handleTimeout(int token, Object obj) {
1767 // Notify any synchronous waiters
1768 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001769 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001770 op = mCurrentOperations.get(token);
1771 if (MORE_DEBUG) {
1772 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1773 + " but no op found");
1774 }
1775 int state = (op != null) ? op.state : OP_TIMEOUT;
1776 if (state == OP_PENDING) {
1777 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1778 op.state = OP_TIMEOUT;
1779 mCurrentOperations.put(token, op);
1780 }
1781 mCurrentOpLock.notifyAll();
1782 }
1783
1784 // If there's a TimeoutHandler for this event, call it
1785 if (op != null && op.callback != null) {
1786 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001787 }
Christopher Tate44a27902010-01-27 17:15:49 -08001788 }
1789
Christopher Tate043dadc2009-06-02 16:11:00 -07001790 // ----- Back up a set of applications via a worker thread -----
1791
Christopher Tate8e294d42011-08-31 20:37:12 -07001792 enum BackupState {
1793 INITIAL,
1794 RUNNING_QUEUE,
1795 FINAL
1796 }
1797
1798 class PerformBackupTask implements BackupRestoreTask {
1799 private static final String TAG = "PerformBackupTask";
1800
Christopher Tateaa088442009-06-16 18:25:46 -07001801 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001802 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001803 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001804 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001805 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001806 BackupState mCurrentState;
1807
1808 // carried information about the current in-flight operation
1809 PackageInfo mCurrentPackage;
1810 File mSavedStateName;
1811 File mBackupDataName;
1812 File mNewStateName;
1813 ParcelFileDescriptor mSavedState;
1814 ParcelFileDescriptor mBackupData;
1815 ParcelFileDescriptor mNewState;
1816 int mStatus;
1817 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001818
Christopher Tate44a27902010-01-27 17:15:49 -08001819 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001820 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001821 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001822 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001823 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001824
1825 try {
1826 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1827 } catch (RemoteException e) {
1828 // can't happen; the transport is local
1829 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001830
1831 mCurrentState = BackupState.INITIAL;
1832 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001833
1834 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001835 }
1836
Christopher Tate8e294d42011-08-31 20:37:12 -07001837 // Main entry point: perform one chunk of work, updating the state as appropriate
1838 // and reposting the next chunk to the primary backup handler thread.
1839 @Override
1840 public void execute() {
1841 switch (mCurrentState) {
1842 case INITIAL:
1843 beginBackup();
1844 break;
1845
1846 case RUNNING_QUEUE:
1847 invokeNextAgent();
1848 break;
1849
1850 case FINAL:
1851 if (!mFinished) finalizeBackup();
1852 else {
1853 Slog.e(TAG, "Duplicate finish");
1854 }
Christopher Tate2982d062011-09-06 20:35:24 -07001855 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001856 break;
1857 }
1858 }
1859
1860 // We're starting a backup pass. Initialize the transport and send
1861 // the PM metadata blob if we haven't already.
1862 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001863 if (DEBUG_BACKUP_TRACE) {
1864 clearBackupTrace();
1865 StringBuilder b = new StringBuilder(256);
1866 b.append("beginBackup: [");
1867 for (BackupRequest req : mOriginalQueue) {
1868 b.append(' ');
1869 b.append(req.packageName);
1870 }
1871 b.append(" ]");
1872 addBackupTrace(b.toString());
1873 }
1874
Christopher Tate8e294d42011-08-31 20:37:12 -07001875 mStatus = BackupConstants.TRANSPORT_OK;
1876
1877 // Sanity check: if the queue is empty we have no work to do.
1878 if (mOriginalQueue.isEmpty()) {
1879 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001880 addBackupTrace("queue empty at begin");
1881 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001882 return;
1883 }
1884
1885 // We need to retain the original queue contents in case of transport
1886 // failure, but we want a working copy that we can manipulate along
1887 // the way.
1888 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1889
Joe Onorato8a9b2202010-02-26 18:56:32 -08001890 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001891
Christopher Tate8e294d42011-08-31 20:37:12 -07001892 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001893 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001894 final String transportName = mTransport.transportDirName();
1895 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001896
Dan Egnor852f8e42009-09-30 11:20:45 -07001897 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001898 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001899 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001900 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001901 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001902 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001903
1904 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001905 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001907 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001908 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001909 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001910 }
Dan Egnor01445162009-09-21 17:04:05 -07001911 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001912
1913 // The package manager doesn't have a proper <application> etc, but since
1914 // it's running here in the system process we can just set up its agent
1915 // directly and use a synthetic BackupRequest. We always run this pass
1916 // because it's cheap and this way we guarantee that we don't get out of
1917 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001918 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001919 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1920 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001921 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001922 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001923 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001924 }
Christopher Tate90967f42009-09-20 15:28:33 -07001925
Christopher Tate8e294d42011-08-31 20:37:12 -07001926 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1927 // The backend reports that our dataset has been wiped. Note this in
1928 // the event log; the no-success code below will reset the backup
1929 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001930 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001931 }
1932 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001933 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001934 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001935 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001936 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001937 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1938 // metadata and its completion/timeout callback will continue the state
1939 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001940 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001941 if (mStatus != BackupConstants.TRANSPORT_OK) {
1942 // if things went wrong at this point, we need to
1943 // restage everything and try again later.
1944 resetBackupState(mStateDir); // Just to make sure.
1945 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001946 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001947 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001948 }
1949
Christopher Tate8e294d42011-08-31 20:37:12 -07001950 // Transport has been initialized and the PM metadata submitted successfully
1951 // if that was warranted. Now we process the single next thing in the queue.
1952 void invokeNextAgent() {
1953 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001954 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001955
Christopher Tate8e294d42011-08-31 20:37:12 -07001956 // Sanity check that we have work to do. If not, skip to the end where
1957 // we reestablish the wakelock invariants etc.
1958 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001959 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001960 executeNextState(BackupState.FINAL);
1961 return;
1962 }
1963
1964 // pop the entry we're going to process on this step
1965 BackupRequest request = mQueue.get(0);
1966 mQueue.remove(0);
1967
1968 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001969 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001970
1971 // Verify that the requested app exists; it might be something that
1972 // requested a backup but was then uninstalled. The request was
1973 // journalled and rather than tamper with the journal it's safer
1974 // to sanity-check here. This also gives us the classname of the
1975 // package's backup agent.
1976 try {
1977 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1978 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001979 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1980 // The manifest has changed but we had a stale backup request pending.
1981 // This won't happen again because the app won't be requesting further
1982 // backups.
1983 Slog.i(TAG, "Package " + request.packageName
1984 + " no longer supports backup; skipping");
1985 addBackupTrace("skipping - no agent, completion is noop");
1986 executeNextState(BackupState.RUNNING_QUEUE);
1987 return;
1988 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001989
Christopher Tate043dadc2009-06-02 16:11:00 -07001990 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001991 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001992 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1993 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001994 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001995 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001996 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1998 // at this point we'll either get a completion callback from the
1999 // agent, or a timeout message on the main handler. either way, we're
2000 // done here as long as we're successful so far.
2001 } else {
2002 // Timeout waiting for the agent
2003 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002004 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002005 } catch (SecurityException ex) {
2006 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002007 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002008 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002009 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002010 }
2011 } catch (NameNotFoundException e) {
2012 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002013 addBackupTrace("no such package");
2014 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002015 } finally {
2016 mWakelock.setWorkSource(null);
2017
2018 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002019 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002020 if (mStatus != BackupConstants.TRANSPORT_OK) {
2021 BackupState nextState = BackupState.RUNNING_QUEUE;
2022
2023 // An agent-level failure means we reenqueue this one agent for
2024 // a later retry, but otherwise proceed normally.
2025 if (mStatus == BackupConstants.AGENT_ERROR) {
2026 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2027 + " - restaging");
2028 dataChangedImpl(request.packageName);
2029 mStatus = BackupConstants.TRANSPORT_OK;
2030 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002031 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2032 // Failed lookup of the app, so we couldn't bring up an agent, but
2033 // we're otherwise fine. Just drop it and go on to the next as usual.
2034 mStatus = BackupConstants.TRANSPORT_OK;
2035 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002036 // Transport-level failure means we reenqueue everything
2037 revertAndEndBackup();
2038 nextState = BackupState.FINAL;
2039 }
2040
2041 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002042 } else {
2043 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002044 }
2045 }
2046 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002047
Christopher Tate8e294d42011-08-31 20:37:12 -07002048 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002049 addBackupTrace("finishing");
2050
Christopher Tate8e294d42011-08-31 20:37:12 -07002051 // Either backup was successful, in which case we of course do not need
2052 // this pass's journal any more; or it failed, in which case we just
2053 // re-enqueued all of these packages in the current active journal.
2054 // Either way, we no longer need this pass's journal.
2055 if (mJournal != null && !mJournal.delete()) {
2056 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2057 }
2058
2059 // If everything actually went through and this is the first time we've
2060 // done a backup, we can now record what the current backup dataset token
2061 // is.
2062 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002063 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002064 try {
2065 mCurrentToken = mTransport.getCurrentRestoreSet();
2066 } catch (RemoteException e) {} // can't happen
2067 writeRestoreTokens();
2068 }
2069
Christopher Tate336a6492011-10-05 16:05:43 -07002070 // Set up the next backup pass - at this point we can set mBackupRunning
2071 // to false to allow another pass to fire, because we're done with the
2072 // state machine sequence and the wakelock is refcounted.
2073 synchronized (mQueueLock) {
2074 mBackupRunning = false;
2075 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002076 // Make sure we back up everything and perform the one-time init
2077 clearMetadata();
2078 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002079 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002080 backupNow();
2081 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002082 }
2083
2084 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002085 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002086 Slog.i(TAG, "Backup pass finished.");
2087 mWakelock.release();
2088 }
2089
Christopher Tatee659fb92011-10-10 16:34:50 -07002090 // Remove the PM metadata state. This will generate an init on the next pass.
2091 void clearMetadata() {
2092 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2093 if (pmState.exists()) pmState.delete();
2094 }
2095
Christopher Tate8e294d42011-08-31 20:37:12 -07002096 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2097 // handler in case it doesn't get back to us.
2098 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002099 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002100 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2101 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002102
Christopher Tate8e294d42011-08-31 20:37:12 -07002103 mSavedStateName = new File(mStateDir, packageName);
2104 mBackupDataName = new File(mDataDir, packageName + ".data");
2105 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002106
Christopher Tate8e294d42011-08-31 20:37:12 -07002107 mSavedState = null;
2108 mBackupData = null;
2109 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002110
Christopher Tate4a627c72011-04-01 14:43:32 -07002111 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002112 try {
2113 // Look up the package info & signatures. This is first so that if it
2114 // throws an exception, there's no file setup yet that would need to
2115 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002116 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002117 // The metadata 'package' is synthetic; construct one and make
2118 // sure our global state is pointed at it
2119 mCurrentPackage = new PackageInfo();
2120 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002121 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002122
Christopher Tatec7b31e32009-06-10 15:49:30 -07002123 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002124 // the saved-state "file". This is by definition an incremental,
2125 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002126 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002127 ParcelFileDescriptor.MODE_READ_ONLY |
2128 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002129
Christopher Tate8e294d42011-08-31 20:37:12 -07002130 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002131 ParcelFileDescriptor.MODE_READ_WRITE |
2132 ParcelFileDescriptor.MODE_CREATE |
2133 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002134
Christopher Tate8e294d42011-08-31 20:37:12 -07002135 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002136 ParcelFileDescriptor.MODE_READ_WRITE |
2137 ParcelFileDescriptor.MODE_CREATE |
2138 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002139
Christopher Tate44a27902010-01-27 17:15:49 -08002140 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002141 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002142 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002143 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002145 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002146 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002147 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002148 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2149 e.toString());
2150 agentErrorCleanup();
2151 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002152 }
2153
Christopher Tate8e294d42011-08-31 20:37:12 -07002154 // At this point the agent is off and running. The next thing to happen will
2155 // either be a callback from the agent, at which point we'll process its data
2156 // for transport, or a timeout. Either way the next phase will happen in
2157 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002158 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002159 return BackupConstants.TRANSPORT_OK;
2160 }
2161
2162 @Override
2163 public void operationComplete() {
2164 // Okay, the agent successfully reported back to us. Spin the data off to the
2165 // transport and proceed with the next stage.
2166 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2167 + mCurrentPackage.packageName);
2168 mBackupHandler.removeMessages(MSG_TIMEOUT);
2169 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002170 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002171
2172 ParcelFileDescriptor backupData = null;
2173 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002174 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002175 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002176 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002177 if (mStatus == BackupConstants.TRANSPORT_OK) {
2178 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002179 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002180 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002181 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002182 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002183
Dan Egnor83861e72009-09-17 16:17:55 -07002184 // TODO - We call finishBackup() for each application backed up, because
2185 // we need to know now whether it succeeded or failed. Instead, we should
2186 // hold off on finishBackup() until the end, which implies holding off on
2187 // renaming *all* the output state files (see below) until that happens.
2188
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002191 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002192 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002193 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002194 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002195 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002196 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002197 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002198 }
2199
2200 // After successful transport, delete the now-stale data
2201 // and juggle the files so that next time we supply the agent
2202 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002203 if (mStatus == BackupConstants.TRANSPORT_OK) {
2204 mBackupDataName.delete();
2205 mNewStateName.renameTo(mSavedStateName);
2206 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2207 mCurrentPackage.packageName, size);
2208 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002209 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002210 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2211 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002212 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002213 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002214 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2215 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2216 mCurrentPackage.packageName);
2217 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002218 } finally {
2219 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002220 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002221
Christopher Tate8e294d42011-08-31 20:37:12 -07002222 // If we encountered an error here it's a transport-level failure. That
2223 // means we need to halt everything and reschedule everything for next time.
2224 final BackupState nextState;
2225 if (mStatus != BackupConstants.TRANSPORT_OK) {
2226 revertAndEndBackup();
2227 nextState = BackupState.FINAL;
2228 } else {
2229 // Success! Proceed with the next app if any, otherwise we're done.
2230 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2231 }
2232
2233 executeNextState(nextState);
2234 }
2235
2236 @Override
2237 public void handleTimeout() {
2238 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2239 // it for the next time we run a backup pass.
2240 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2241 // fail repeatedly (i.e. have proved themselves to be buggy).
2242 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2243 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2244 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002245 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002246 agentErrorCleanup();
2247 dataChangedImpl(mCurrentPackage.packageName);
2248 }
2249
2250 void revertAndEndBackup() {
2251 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002252 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002253 for (BackupRequest request : mOriginalQueue) {
2254 dataChangedImpl(request.packageName);
2255 }
2256 // We also want to reset the backup schedule based on whatever
2257 // the transport suggests by way of retry/backoff time.
2258 restartBackupAlarm();
2259 }
2260
2261 void agentErrorCleanup() {
2262 mBackupDataName.delete();
2263 mNewStateName.delete();
2264 clearAgentState();
2265
2266 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2267 }
2268
2269 // Cleanup common to both success and failure cases
2270 void clearAgentState() {
2271 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2272 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2273 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2274 mSavedState = mBackupData = mNewState = null;
2275 synchronized (mCurrentOpLock) {
2276 mCurrentOperations.clear();
2277 }
2278
2279 // If this was a pseudopackage there's no associated Activity Manager state
2280 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002281 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002282 try { // unbind even on timeout, just in case
2283 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2284 } catch (RemoteException e) {}
2285 }
2286 }
2287
2288 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002289 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002290 synchronized (mQueueLock) {
2291 try {
2292 startBackupAlarmsLocked(mTransport.requestBackupTime());
2293 } catch (RemoteException e) { /* cannot happen */ }
2294 }
2295 }
2296
2297 void executeNextState(BackupState nextState) {
2298 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2299 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002300 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002301 mCurrentState = nextState;
2302 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2303 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002304 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002305 }
2306
Christopher Tatedf01dea2009-06-09 20:45:02 -07002307
Christopher Tate4a627c72011-04-01 14:43:32 -07002308 // ----- Full backup to a file/socket -----
2309
2310 class PerformFullBackupTask implements Runnable {
2311 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002312 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002313 IFullBackupRestoreObserver mObserver;
2314 boolean mIncludeApks;
2315 boolean mIncludeShared;
2316 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002317 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002318 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002319 String mCurrentPassword;
2320 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002321 AtomicBoolean mLatchObject;
2322 File mFilesDir;
2323 File mManifestFile;
2324
Christopher Tate7926a692011-07-11 11:31:57 -07002325 class FullBackupRunner implements Runnable {
2326 PackageInfo mPackage;
2327 IBackupAgent mAgent;
2328 ParcelFileDescriptor mPipe;
2329 int mToken;
2330 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002331 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002332
2333 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002334 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002335 mPackage = pack;
2336 mAgent = agent;
2337 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2338 mToken = token;
2339 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002340 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002341 }
2342
2343 @Override
2344 public void run() {
2345 try {
2346 BackupDataOutput output = new BackupDataOutput(
2347 mPipe.getFileDescriptor());
2348
Christopher Tate73d73692012-01-20 17:11:31 -08002349 if (mWriteManifest) {
2350 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2351 writeAppManifest(mPackage, mManifestFile, mSendApk);
2352 FullBackup.backupToTar(mPackage.packageName, null, null,
2353 mFilesDir.getAbsolutePath(),
2354 mManifestFile.getAbsolutePath(),
2355 output);
2356 }
Christopher Tate7926a692011-07-11 11:31:57 -07002357
2358 if (mSendApk) {
2359 writeApkToBackup(mPackage, output);
2360 }
2361
Christopher Tatec58efa62011-08-01 19:20:14 -07002362 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002363 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002364 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2365 } catch (IOException e) {
2366 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2367 } catch (RemoteException e) {
2368 Slog.e(TAG, "Remote agent vanished during full backup of "
2369 + mPackage.packageName);
2370 } finally {
2371 try {
2372 mPipe.close();
2373 } catch (IOException e) {}
2374 }
2375 }
2376 }
2377
Christopher Tate4a627c72011-04-01 14:43:32 -07002378 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002379 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002380 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002381 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002382 mOutputFile = fd;
2383 mObserver = observer;
2384 mIncludeApks = includeApks;
2385 mIncludeShared = includeShared;
2386 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002387 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002388 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002389 mCurrentPassword = curPassword;
2390 // when backing up, if there is a current backup password, we require that
2391 // the user use a nonempty encryption password as well. if one is supplied
2392 // in the UI we use that, but if the UI was left empty we fall back to the
2393 // current backup password (which was supplied by the user as well).
2394 if (encryptPassword == null || "".equals(encryptPassword)) {
2395 mEncryptPassword = curPassword;
2396 } else {
2397 mEncryptPassword = encryptPassword;
2398 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002399 mLatchObject = latch;
2400
2401 mFilesDir = new File("/data/system");
2402 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2403 }
2404
2405 @Override
2406 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002407 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002408
Christopher Tateb0628bf2011-06-02 15:08:13 -07002409 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002410 sendStartBackup();
2411
2412 // doAllApps supersedes the package set if any
2413 if (mAllApps) {
2414 packagesToBackup = mPackageManager.getInstalledPackages(
2415 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002416 // Exclude system apps if we've been asked to do so
2417 if (mIncludeSystem == false) {
2418 for (int i = 0; i < packagesToBackup.size(); ) {
2419 PackageInfo pkg = packagesToBackup.get(i);
2420 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2421 packagesToBackup.remove(i);
2422 } else {
2423 i++;
2424 }
2425 }
2426 }
2427 }
2428
2429 // Now process the command line argument packages, if any. Note that explicitly-
2430 // named system-partition packages will be included even if includeSystem was
2431 // set to false.
2432 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002433 for (String pkgName : mPackages) {
2434 try {
2435 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2436 PackageManager.GET_SIGNATURES));
2437 } catch (NameNotFoundException e) {
2438 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2439 }
2440 }
2441 }
2442
Christopher Tate73d73692012-01-20 17:11:31 -08002443 // Cull any packages that have indicated that backups are not permitted, as well
2444 // as any explicit mention of the 'special' shared-storage agent package (we
2445 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002446 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002447 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002448 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2449 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002450 packagesToBackup.remove(i);
2451 } else {
2452 i++;
2453 }
2454 }
2455
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002456 // Cull any packages that run as system-domain uids but do not define their
2457 // own backup agents
2458 for (int i = 0; i < packagesToBackup.size(); ) {
2459 PackageInfo pkg = packagesToBackup.get(i);
2460 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2461 && (pkg.applicationInfo.backupAgentName == null)) {
2462 if (MORE_DEBUG) {
2463 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2464 }
2465 packagesToBackup.remove(i);
2466 } else {
2467 i++;
2468 }
2469 }
2470
Christopher Tate7926a692011-07-11 11:31:57 -07002471 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002472 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002473
Christopher Tate4a627c72011-04-01 14:43:32 -07002474 PackageInfo pkg = null;
2475 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002476 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002477 boolean compressing = COMPRESS_FULL_BACKUPS;
2478 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002479
Christopher Tateeef4ae42011-08-05 13:15:53 -07002480 // Verify that the given password matches the currently-active
2481 // backup password, if any
2482 if (hasBackupPassword()) {
2483 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2484 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2485 return;
2486 }
2487 }
2488
Christopher Tate7bdb0962011-07-13 19:30:21 -07002489 // Write the global file header. All strings are UTF-8 encoded; lines end
2490 // with a '\n' byte. Actual backup data begins immediately following the
2491 // final '\n'.
2492 //
2493 // line 1: "ANDROID BACKUP"
2494 // line 2: backup file format version, currently "1"
2495 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002496 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2497 //
2498 // When line 4 is not "none", then additional header data follows:
2499 //
2500 // line 5: user password salt [hex]
2501 // line 6: master key checksum salt [hex]
2502 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2503 // line 8: IV of the user key [hex]
2504 // line 9: master key blob [hex]
2505 // IV of the master key, master key itself, master key checksum hash
2506 //
2507 // The master key checksum is the master key plus its checksum salt, run through
2508 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2509 // correct password for decrypting the archive: the master key decrypted from
2510 // the archive using the user-supplied password is also run through PBKDF2 in
2511 // this way, and if the result does not match the checksum as stored in the
2512 // archive, then we know that the user-supplied password does not match the
2513 // archive's.
2514 StringBuilder headerbuf = new StringBuilder(1024);
2515
Christopher Tate7bdb0962011-07-13 19:30:21 -07002516 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002517 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2518 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002519
2520 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002521 // Set up the encryption stage if appropriate, and emit the correct header
2522 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002523 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2524 } else {
2525 headerbuf.append("none\n");
2526 }
2527
Christopher Tate7bdb0962011-07-13 19:30:21 -07002528 byte[] header = headerbuf.toString().getBytes("UTF-8");
2529 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002530
2531 // Set up the compression stage feeding into the encryption stage (if any)
2532 if (compressing) {
2533 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2534 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2535 }
2536
2537 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002538 } catch (Exception e) {
2539 // Should never happen!
2540 Slog.e(TAG, "Unable to emit archive header", e);
2541 return;
2542 }
2543
Christopher Tate73d73692012-01-20 17:11:31 -08002544 // Shared storage if requested
2545 if (mIncludeShared) {
2546 try {
2547 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2548 packagesToBackup.add(pkg);
2549 } catch (NameNotFoundException e) {
2550 Slog.e(TAG, "Unable to find shared-storage backup handler");
2551 }
2552 }
2553
Christopher Tateb0628bf2011-06-02 15:08:13 -07002554 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002555 int N = packagesToBackup.size();
2556 for (int i = 0; i < N; i++) {
2557 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002558 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002559 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002560
Christopher Tate6853fcf2011-08-10 17:52:21 -07002561 // Done!
2562 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002563 } catch (RemoteException e) {
2564 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002565 } catch (Exception e) {
2566 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002567 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002568 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002569 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002570 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002571 mOutputFile.close();
2572 } catch (IOException e) {
2573 /* nothing we can do about this */
2574 }
2575 synchronized (mCurrentOpLock) {
2576 mCurrentOperations.clear();
2577 }
2578 synchronized (mLatchObject) {
2579 mLatchObject.set(true);
2580 mLatchObject.notifyAll();
2581 }
2582 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002583 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002584 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002585 }
2586 }
2587
Christopher Tate2efd2db2011-07-19 16:32:49 -07002588 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2589 OutputStream ofstream) throws Exception {
2590 // User key will be used to encrypt the master key.
2591 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002592 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002593 PBKDF2_HASH_ROUNDS);
2594
2595 // the master key is random for each backup
2596 byte[] masterPw = new byte[256 / 8];
2597 mRng.nextBytes(masterPw);
2598 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2599
2600 // primary encryption of the datastream with the random key
2601 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2602 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2603 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2604 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2605
2606 // line 4: name of encryption algorithm
2607 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2608 headerbuf.append('\n');
2609 // line 5: user password salt [hex]
2610 headerbuf.append(byteArrayToHex(newUserSalt));
2611 headerbuf.append('\n');
2612 // line 6: master key checksum salt [hex]
2613 headerbuf.append(byteArrayToHex(checksumSalt));
2614 headerbuf.append('\n');
2615 // line 7: number of PBKDF2 rounds used [decimal]
2616 headerbuf.append(PBKDF2_HASH_ROUNDS);
2617 headerbuf.append('\n');
2618
2619 // line 8: IV of the user key [hex]
2620 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2621 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2622
2623 byte[] IV = mkC.getIV();
2624 headerbuf.append(byteArrayToHex(IV));
2625 headerbuf.append('\n');
2626
2627 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2628 // [byte] IV length = Niv
2629 // [array of Niv bytes] IV itself
2630 // [byte] master key length = Nmk
2631 // [array of Nmk bytes] master key itself
2632 // [byte] MK checksum hash length = Nck
2633 // [array of Nck bytes] master key checksum hash
2634 //
2635 // The checksum is the (master key + checksum salt), run through the
2636 // stated number of PBKDF2 rounds
2637 IV = c.getIV();
2638 byte[] mk = masterKeySpec.getEncoded();
2639 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2640 checksumSalt, PBKDF2_HASH_ROUNDS);
2641
2642 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2643 + checksum.length + 3);
2644 DataOutputStream mkOut = new DataOutputStream(blob);
2645 mkOut.writeByte(IV.length);
2646 mkOut.write(IV);
2647 mkOut.writeByte(mk.length);
2648 mkOut.write(mk);
2649 mkOut.writeByte(checksum.length);
2650 mkOut.write(checksum);
2651 mkOut.flush();
2652 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2653 headerbuf.append(byteArrayToHex(encryptedMk));
2654 headerbuf.append('\n');
2655
2656 return finalOutput;
2657 }
2658
2659 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002660 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002661 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2662
2663 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2664 IApplicationThread.BACKUP_MODE_FULL);
2665 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002666 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002667 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002668 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002669
Christopher Tateb0628bf2011-06-02 15:08:13 -07002670 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002671 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002672 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002673 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002674 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2675 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2676 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2677
Christopher Tate73d73692012-01-20 17:11:31 -08002678 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002679
Christopher Tate7926a692011-07-11 11:31:57 -07002680 final int token = generateToken();
2681 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002682 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002683 pipes[1].close(); // the runner has dup'd it
2684 pipes[1] = null;
2685 Thread t = new Thread(runner);
2686 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002687
Christopher Tate7926a692011-07-11 11:31:57 -07002688 // Now pull data from the app and stuff it into the compressor
2689 try {
2690 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2691 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002692
Christopher Tate7926a692011-07-11 11:31:57 -07002693 byte[] buffer = new byte[16 * 1024];
2694 int chunkTotal;
2695 while ((chunkTotal = in.readInt()) > 0) {
2696 while (chunkTotal > 0) {
2697 int toRead = (chunkTotal > buffer.length)
2698 ? buffer.length : chunkTotal;
2699 int nRead = in.read(buffer, 0, toRead);
2700 out.write(buffer, 0, nRead);
2701 chunkTotal -= nRead;
2702 }
2703 }
2704 } catch (IOException e) {
2705 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002706 }
2707
Christopher Tateb0628bf2011-06-02 15:08:13 -07002708 if (!waitUntilOperationComplete(token)) {
2709 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2710 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002711 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002712 }
Christopher Tate7926a692011-07-11 11:31:57 -07002713
Christopher Tateb0628bf2011-06-02 15:08:13 -07002714 } catch (IOException e) {
2715 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002716 } finally {
2717 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002718 // flush after every package
2719 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002720 if (pipes != null) {
2721 if (pipes[0] != null) pipes[0].close();
2722 if (pipes[1] != null) pipes[1].close();
2723 }
Christopher Tate7926a692011-07-11 11:31:57 -07002724 } catch (IOException e) {
2725 Slog.w(TAG, "Error bringing down backup stack");
2726 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002727 }
2728 } else {
2729 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2730 }
2731 tearDown(pkg);
2732 }
2733
Christopher Tate79ec80d2011-06-24 14:58:49 -07002734 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2735 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2736 final String appSourceDir = pkg.applicationInfo.sourceDir;
2737 final String apkDir = new File(appSourceDir).getParent();
2738 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2739 apkDir, appSourceDir, output);
2740
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002741 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2742 // doesn't have access to external storage.
2743
Christopher Tate79ec80d2011-06-24 14:58:49 -07002744 // Save associated .obb content if it exists and we did save the apk
2745 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002746 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2747 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002748 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002749 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002750 File[] obbFiles = obbDir.listFiles();
2751 if (obbFiles != null) {
2752 final String obbDirName = obbDir.getAbsolutePath();
2753 for (File obb : obbFiles) {
2754 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2755 obbDirName, obb.getAbsolutePath(), output);
2756 }
2757 }
2758 }
2759 }
2760
Christopher Tate6853fcf2011-08-10 17:52:21 -07002761 private void finalizeBackup(OutputStream out) {
2762 try {
2763 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2764 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2765 out.write(eof);
2766 } catch (IOException e) {
2767 Slog.w(TAG, "Error attempting to finalize backup stream");
2768 }
2769 }
2770
Christopher Tate4a627c72011-04-01 14:43:32 -07002771 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2772 throws IOException {
2773 // Manifest format. All data are strings ending in LF:
2774 // BACKUP_MANIFEST_VERSION, currently 1
2775 //
2776 // Version 1:
2777 // package name
2778 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002779 // platform versionCode
2780 // getInstallerPackageName() for this package (maybe empty)
2781 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002782 // number of signatures == N
2783 // N*: signature byte array in ascii format per Signature.toCharsString()
2784 StringBuilder builder = new StringBuilder(4096);
2785 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2786
2787 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2788 printer.println(pkg.packageName);
2789 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002790 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2791
2792 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2793 printer.println((installerName != null) ? installerName : "");
2794
Christopher Tate4a627c72011-04-01 14:43:32 -07002795 printer.println(withApk ? "1" : "0");
2796 if (pkg.signatures == null) {
2797 printer.println("0");
2798 } else {
2799 printer.println(Integer.toString(pkg.signatures.length));
2800 for (Signature sig : pkg.signatures) {
2801 printer.println(sig.toCharsString());
2802 }
2803 }
2804
2805 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002806 outstream.write(builder.toString().getBytes());
2807 outstream.close();
2808 }
2809
2810 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002811 if (pkg != null) {
2812 final ApplicationInfo app = pkg.applicationInfo;
2813 if (app != null) {
2814 try {
2815 // unbind and tidy up even on timeout or failure, just in case
2816 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002817
Christopher Tateb0628bf2011-06-02 15:08:13 -07002818 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002819 if (app.uid != Process.SYSTEM_UID
2820 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002821 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002822 mActivityManager.killApplicationProcess(app.processName, app.uid);
2823 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002824 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002825 }
2826 } catch (RemoteException e) {
2827 Slog.d(TAG, "Lost app trying to shut down");
2828 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002829 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002830 }
2831 }
2832
2833 // wrappers for observer use
2834 void sendStartBackup() {
2835 if (mObserver != null) {
2836 try {
2837 mObserver.onStartBackup();
2838 } catch (RemoteException e) {
2839 Slog.w(TAG, "full backup observer went away: startBackup");
2840 mObserver = null;
2841 }
2842 }
2843 }
2844
2845 void sendOnBackupPackage(String name) {
2846 if (mObserver != null) {
2847 try {
2848 // TODO: use a more user-friendly name string
2849 mObserver.onBackupPackage(name);
2850 } catch (RemoteException e) {
2851 Slog.w(TAG, "full backup observer went away: backupPackage");
2852 mObserver = null;
2853 }
2854 }
2855 }
2856
2857 void sendEndBackup() {
2858 if (mObserver != null) {
2859 try {
2860 mObserver.onEndBackup();
2861 } catch (RemoteException e) {
2862 Slog.w(TAG, "full backup observer went away: endBackup");
2863 mObserver = null;
2864 }
2865 }
2866 }
2867 }
2868
2869
Christopher Tate75a99702011-05-18 16:28:19 -07002870 // ----- Full restore from a file/socket -----
2871
2872 // Description of a file in the restore datastream
2873 static class FileMetadata {
2874 String packageName; // name of the owning app
2875 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002876 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002877 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2878 String path; // subpath within the semantic domain
2879 long mode; // e.g. 0666 (actually int)
2880 long mtime; // last mod time, UTC time_t (actually int)
2881 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002882
2883 @Override
2884 public String toString() {
2885 StringBuilder sb = new StringBuilder(128);
2886 sb.append("FileMetadata{");
2887 sb.append(packageName); sb.append(',');
2888 sb.append(type); sb.append(',');
2889 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2890 sb.append(size);
2891 sb.append('}');
2892 return sb.toString();
2893 }
Christopher Tate75a99702011-05-18 16:28:19 -07002894 }
2895
2896 enum RestorePolicy {
2897 IGNORE,
2898 ACCEPT,
2899 ACCEPT_IF_APK
2900 }
2901
2902 class PerformFullRestoreTask implements Runnable {
2903 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002904 String mCurrentPassword;
2905 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002906 IFullBackupRestoreObserver mObserver;
2907 AtomicBoolean mLatchObject;
2908 IBackupAgent mAgent;
2909 String mAgentPackage;
2910 ApplicationInfo mTargetApp;
2911 ParcelFileDescriptor[] mPipes = null;
2912
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002913 long mBytes;
2914
Christopher Tate75a99702011-05-18 16:28:19 -07002915 // possible handling states for a given package in the restore dataset
2916 final HashMap<String, RestorePolicy> mPackagePolicies
2917 = new HashMap<String, RestorePolicy>();
2918
2919 // installer package names for each encountered app, derived from the manifests
2920 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2921
2922 // Signatures for a given package found in its manifest file
2923 final HashMap<String, Signature[]> mManifestSignatures
2924 = new HashMap<String, Signature[]>();
2925
2926 // Packages we've already wiped data on when restoring their first file
2927 final HashSet<String> mClearedPackages = new HashSet<String>();
2928
Christopher Tate728a1c42011-07-28 18:03:03 -07002929 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002930 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002931 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002932 mCurrentPassword = curPassword;
2933 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002934 mObserver = observer;
2935 mLatchObject = latch;
2936 mAgent = null;
2937 mAgentPackage = null;
2938 mTargetApp = null;
2939
2940 // Which packages we've already wiped data on. We prepopulate this
2941 // with a whitelist of packages known to be unclearable.
2942 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002943 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002944
Christopher Tate75a99702011-05-18 16:28:19 -07002945 }
2946
2947 class RestoreFileRunnable implements Runnable {
2948 IBackupAgent mAgent;
2949 FileMetadata mInfo;
2950 ParcelFileDescriptor mSocket;
2951 int mToken;
2952
2953 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2954 ParcelFileDescriptor socket, int token) throws IOException {
2955 mAgent = agent;
2956 mInfo = info;
2957 mToken = token;
2958
2959 // This class is used strictly for process-local binder invocations. The
2960 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2961 // do not automatically get a 'dup'ed descriptor that we can can continue
2962 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2963 // before proceeding to do the restore.
2964 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2965 }
2966
2967 @Override
2968 public void run() {
2969 try {
2970 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2971 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2972 mToken, mBackupManagerBinder);
2973 } catch (RemoteException e) {
2974 // never happens; this is used strictly for local binder calls
2975 }
2976 }
2977 }
2978
2979 @Override
2980 public void run() {
2981 Slog.i(TAG, "--- Performing full-dataset restore ---");
2982 sendStartRestore();
2983
Christopher Tateb0628bf2011-06-02 15:08:13 -07002984 // Are we able to restore shared-storage data?
2985 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002986 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002987 }
2988
Christopher Tate2efd2db2011-07-19 16:32:49 -07002989 FileInputStream rawInStream = null;
2990 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002991 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002992 if (hasBackupPassword()) {
2993 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2994 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2995 return;
2996 }
2997 }
2998
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002999 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003000 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003001 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3002 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003003
3004 // First, parse out the unencrypted/uncompressed header
3005 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003006 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003007 final InputStream in;
3008
3009 boolean okay = false;
3010 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3011 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003012 rawDataIn.readFully(streamHeader);
3013 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3014 if (Arrays.equals(magicBytes, streamHeader)) {
3015 // okay, header looks good. now parse out the rest of the fields.
3016 String s = readHeaderLine(rawInStream);
3017 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3018 // okay, it's a version we recognize
3019 s = readHeaderLine(rawInStream);
3020 compressed = (Integer.parseInt(s) != 0);
3021 s = readHeaderLine(rawInStream);
3022 if (s.equals("none")) {
3023 // no more header to parse; we're good to go
3024 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003025 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003026 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3027 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003028 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003029 }
3030 } else Slog.w(TAG, "Archive is encrypted but no password given");
3031 } else Slog.w(TAG, "Wrong header version: " + s);
3032 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003033
3034 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003035 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003036 return;
3037 }
3038
3039 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003040 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003041
3042 boolean didRestore;
3043 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003044 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003045 } while (didRestore);
3046
Christopher Tatec58efa62011-08-01 19:20:14 -07003047 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003048 } catch (IOException e) {
3049 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003050 } finally {
3051 tearDownPipes();
3052 tearDownAgent(mTargetApp);
3053
3054 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003055 if (rawDataIn != null) rawDataIn.close();
3056 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003057 mInputFile.close();
3058 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003059 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003060 /* nothing we can do about this */
3061 }
3062 synchronized (mCurrentOpLock) {
3063 mCurrentOperations.clear();
3064 }
3065 synchronized (mLatchObject) {
3066 mLatchObject.set(true);
3067 mLatchObject.notifyAll();
3068 }
3069 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003070 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003071 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003072 }
3073 }
3074
Christopher Tate7bdb0962011-07-13 19:30:21 -07003075 String readHeaderLine(InputStream in) throws IOException {
3076 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003077 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003078 while ((c = in.read()) >= 0) {
3079 if (c == '\n') break; // consume and discard the newlines
3080 buffer.append((char)c);
3081 }
3082 return buffer.toString();
3083 }
3084
Christopher Tate2efd2db2011-07-19 16:32:49 -07003085 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3086 InputStream result = null;
3087 try {
3088 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3089
3090 String userSaltHex = readHeaderLine(rawInStream); // 5
3091 byte[] userSalt = hexToByteArray(userSaltHex);
3092
3093 String ckSaltHex = readHeaderLine(rawInStream); // 6
3094 byte[] ckSalt = hexToByteArray(ckSaltHex);
3095
3096 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3097 String userIvHex = readHeaderLine(rawInStream); // 8
3098
3099 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3100
3101 // decrypt the master key blob
3102 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003103 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003104 rounds);
3105 byte[] IV = hexToByteArray(userIvHex);
3106 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3107 c.init(Cipher.DECRYPT_MODE,
3108 new SecretKeySpec(userKey.getEncoded(), "AES"),
3109 ivSpec);
3110 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3111 byte[] mkBlob = c.doFinal(mkCipher);
3112
3113 // first, the master key IV
3114 int offset = 0;
3115 int len = mkBlob[offset++];
3116 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3117 offset += len;
3118 // then the master key itself
3119 len = mkBlob[offset++];
3120 byte[] mk = Arrays.copyOfRange(mkBlob,
3121 offset, offset + len);
3122 offset += len;
3123 // and finally the master key checksum hash
3124 len = mkBlob[offset++];
3125 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3126 offset, offset + len);
3127
3128 // now validate the decrypted master key against the checksum
3129 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3130 if (Arrays.equals(calculatedCk, mkChecksum)) {
3131 ivSpec = new IvParameterSpec(IV);
3132 c.init(Cipher.DECRYPT_MODE,
3133 new SecretKeySpec(mk, "AES"),
3134 ivSpec);
3135 // Only if all of the above worked properly will 'result' be assigned
3136 result = new CipherInputStream(rawInStream, c);
3137 } else Slog.w(TAG, "Incorrect password");
3138 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3139 } catch (InvalidAlgorithmParameterException e) {
3140 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3141 } catch (BadPaddingException e) {
3142 // This case frequently occurs when the wrong password is used to decrypt
3143 // the master key. Use the identical "incorrect password" log text as is
3144 // used in the checksum failure log in order to avoid providing additional
3145 // information to an attacker.
3146 Slog.w(TAG, "Incorrect password");
3147 } catch (IllegalBlockSizeException e) {
3148 Slog.w(TAG, "Invalid block size in master key");
3149 } catch (NoSuchAlgorithmException e) {
3150 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3151 } catch (NoSuchPaddingException e) {
3152 Slog.e(TAG, "Needed padding mechanism unavailable!");
3153 } catch (InvalidKeyException e) {
3154 Slog.w(TAG, "Illegal password; aborting");
3155 } catch (NumberFormatException e) {
3156 Slog.w(TAG, "Can't parse restore data header");
3157 } catch (IOException e) {
3158 Slog.w(TAG, "Can't read input header");
3159 }
3160
3161 return result;
3162 }
3163
Christopher Tate75a99702011-05-18 16:28:19 -07003164 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3165 FileMetadata info;
3166 try {
3167 info = readTarHeaders(instream);
3168 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003169 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003170 dumpFileMetadata(info);
3171 }
3172
3173 final String pkg = info.packageName;
3174 if (!pkg.equals(mAgentPackage)) {
3175 // okay, change in package; set up our various
3176 // bookkeeping if we haven't seen it yet
3177 if (!mPackagePolicies.containsKey(pkg)) {
3178 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3179 }
3180
3181 // Clean up the previous agent relationship if necessary,
3182 // and let the observer know we're considering a new app.
3183 if (mAgent != null) {
3184 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3185 tearDownPipes();
3186 tearDownAgent(mTargetApp);
3187 mTargetApp = null;
3188 mAgentPackage = null;
3189 }
3190 }
3191
3192 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3193 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3194 mPackageInstallers.put(pkg, info.installerPackageName);
3195 // We've read only the manifest content itself at this point,
3196 // so consume the footer before looping around to the next
3197 // input file
3198 skipTarPadding(info.size, instream);
3199 sendOnRestorePackage(pkg);
3200 } else {
3201 // Non-manifest, so it's actual file data. Is this a package
3202 // we're ignoring?
3203 boolean okay = true;
3204 RestorePolicy policy = mPackagePolicies.get(pkg);
3205 switch (policy) {
3206 case IGNORE:
3207 okay = false;
3208 break;
3209
3210 case ACCEPT_IF_APK:
3211 // If we're in accept-if-apk state, then the first file we
3212 // see MUST be the apk.
3213 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3214 if (DEBUG) Slog.d(TAG, "APK file; installing");
3215 // Try to install the app.
3216 String installerName = mPackageInstallers.get(pkg);
3217 okay = installApk(info, installerName, instream);
3218 // good to go; promote to ACCEPT
3219 mPackagePolicies.put(pkg, (okay)
3220 ? RestorePolicy.ACCEPT
3221 : RestorePolicy.IGNORE);
3222 // At this point we've consumed this file entry
3223 // ourselves, so just strip the tar footer and
3224 // go on to the next file in the input stream
3225 skipTarPadding(info.size, instream);
3226 return true;
3227 } else {
3228 // File data before (or without) the apk. We can't
3229 // handle it coherently in this case so ignore it.
3230 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3231 okay = false;
3232 }
3233 break;
3234
3235 case ACCEPT:
3236 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3237 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3238 // we can take the data without the apk, so we
3239 // *want* to do so. skip the apk by declaring this
3240 // one file not-okay without changing the restore
3241 // policy for the package.
3242 okay = false;
3243 }
3244 break;
3245
3246 default:
3247 // Something has gone dreadfully wrong when determining
3248 // the restore policy from the manifest. Ignore the
3249 // rest of this package's data.
3250 Slog.e(TAG, "Invalid policy from manifest");
3251 okay = false;
3252 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3253 break;
3254 }
3255
3256 // If the policy is satisfied, go ahead and set up to pipe the
3257 // data to the agent.
3258 if (DEBUG && okay && mAgent != null) {
3259 Slog.i(TAG, "Reusing existing agent instance");
3260 }
3261 if (okay && mAgent == null) {
3262 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3263
3264 try {
3265 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3266
3267 // If we haven't sent any data to this app yet, we probably
3268 // need to clear it first. Check that.
3269 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003270 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003271 // responsible for coherently managing a full
3272 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003273 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003274 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3275 clearApplicationDataSynchronous(pkg);
3276 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003277 if (DEBUG) Slog.d(TAG, "backup agent ("
3278 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003279 }
3280 mClearedPackages.add(pkg);
3281 } else {
3282 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3283 }
3284
3285 // All set; now set up the IPC and launch the agent
3286 setUpPipes();
3287 mAgent = bindToAgentSynchronous(mTargetApp,
3288 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3289 mAgentPackage = pkg;
3290 } catch (IOException e) {
3291 // fall through to error handling
3292 } catch (NameNotFoundException e) {
3293 // fall through to error handling
3294 }
3295
3296 if (mAgent == null) {
3297 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3298 okay = false;
3299 tearDownPipes();
3300 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3301 }
3302 }
3303
3304 // Sanity check: make sure we never give data to the wrong app. This
3305 // should never happen but a little paranoia here won't go amiss.
3306 if (okay && !pkg.equals(mAgentPackage)) {
3307 Slog.e(TAG, "Restoring data for " + pkg
3308 + " but agent is for " + mAgentPackage);
3309 okay = false;
3310 }
3311
3312 // At this point we have an agent ready to handle the full
3313 // restore data as well as a pipe for sending data to
3314 // that agent. Tell the agent to start reading from the
3315 // pipe.
3316 if (okay) {
3317 boolean agentSuccess = true;
3318 long toCopy = info.size;
3319 final int token = generateToken();
3320 try {
3321 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3322 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003323 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003324 // fire up the app's agent listening on the socket. If
3325 // the agent is running in the system process we can't
3326 // just invoke it asynchronously, so we provide a thread
3327 // for it here.
3328 if (mTargetApp.processName.equals("system")) {
3329 Slog.d(TAG, "system process agent - spinning a thread");
3330 RestoreFileRunnable runner = new RestoreFileRunnable(
3331 mAgent, info, mPipes[0], token);
3332 new Thread(runner).start();
3333 } else {
3334 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3335 info.domain, info.path, info.mode, info.mtime,
3336 token, mBackupManagerBinder);
3337 }
3338 } catch (IOException e) {
3339 // couldn't dup the socket for a process-local restore
3340 Slog.d(TAG, "Couldn't establish restore");
3341 agentSuccess = false;
3342 okay = false;
3343 } catch (RemoteException e) {
3344 // whoops, remote agent went away. We'll eat the content
3345 // ourselves, then, and not copy it over.
3346 Slog.e(TAG, "Agent crashed during full restore");
3347 agentSuccess = false;
3348 okay = false;
3349 }
3350
3351 // Copy over the data if the agent is still good
3352 if (okay) {
3353 boolean pipeOkay = true;
3354 FileOutputStream pipe = new FileOutputStream(
3355 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003356 while (toCopy > 0) {
3357 int toRead = (toCopy > buffer.length)
3358 ? buffer.length : (int)toCopy;
3359 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003360 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003361 if (nRead <= 0) break;
3362 toCopy -= nRead;
3363
3364 // send it to the output pipe as long as things
3365 // are still good
3366 if (pipeOkay) {
3367 try {
3368 pipe.write(buffer, 0, nRead);
3369 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003370 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003371 pipeOkay = false;
3372 }
3373 }
3374 }
3375
3376 // done sending that file! Now we just need to consume
3377 // the delta from info.size to the end of block.
3378 skipTarPadding(info.size, instream);
3379
3380 // and now that we've sent it all, wait for the remote
3381 // side to acknowledge receipt
3382 agentSuccess = waitUntilOperationComplete(token);
3383 }
3384
3385 // okay, if the remote end failed at any point, deal with
3386 // it by ignoring the rest of the restore on it
3387 if (!agentSuccess) {
3388 mBackupHandler.removeMessages(MSG_TIMEOUT);
3389 tearDownPipes();
3390 tearDownAgent(mTargetApp);
3391 mAgent = null;
3392 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3393 }
3394 }
3395
3396 // Problems setting up the agent communication, or an already-
3397 // ignored package: skip to the next tar stream entry by
3398 // reading and discarding this file.
3399 if (!okay) {
3400 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3401 long bytesToConsume = (info.size + 511) & ~511;
3402 while (bytesToConsume > 0) {
3403 int toRead = (bytesToConsume > buffer.length)
3404 ? buffer.length : (int)bytesToConsume;
3405 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003406 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003407 if (nRead <= 0) break;
3408 bytesToConsume -= nRead;
3409 }
3410 }
3411 }
3412 }
3413 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003414 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003415 // treat as EOF
3416 info = null;
3417 }
3418
3419 return (info != null);
3420 }
3421
3422 void setUpPipes() throws IOException {
3423 mPipes = ParcelFileDescriptor.createPipe();
3424 }
3425
3426 void tearDownPipes() {
3427 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003428 try {
3429 mPipes[0].close();
3430 mPipes[0] = null;
3431 mPipes[1].close();
3432 mPipes[1] = null;
3433 } catch (IOException e) {
3434 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003435 }
3436 mPipes = null;
3437 }
3438 }
3439
3440 void tearDownAgent(ApplicationInfo app) {
3441 if (mAgent != null) {
3442 try {
3443 // unbind and tidy up even on timeout or failure, just in case
3444 mActivityManager.unbindBackupAgent(app);
3445
3446 // The agent was running with a stub Application object, so shut it down.
3447 // !!! We hardcode the confirmation UI's package name here rather than use a
3448 // manifest flag! TODO something less direct.
3449 if (app.uid != Process.SYSTEM_UID
3450 && !app.packageName.equals("com.android.backupconfirm")) {
3451 if (DEBUG) Slog.d(TAG, "Killing host process");
3452 mActivityManager.killApplicationProcess(app.processName, app.uid);
3453 } else {
3454 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3455 }
3456 } catch (RemoteException e) {
3457 Slog.d(TAG, "Lost app trying to shut down");
3458 }
3459 mAgent = null;
3460 }
3461 }
3462
3463 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3464 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003465 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003466 int mResult;
3467
3468 public void reset() {
3469 synchronized (mDone) {
3470 mDone.set(false);
3471 }
3472 }
3473
3474 public void waitForCompletion() {
3475 synchronized (mDone) {
3476 while (mDone.get() == false) {
3477 try {
3478 mDone.wait();
3479 } catch (InterruptedException e) { }
3480 }
3481 }
3482 }
3483
3484 int getResult() {
3485 return mResult;
3486 }
3487
3488 @Override
3489 public void packageInstalled(String packageName, int returnCode)
3490 throws RemoteException {
3491 synchronized (mDone) {
3492 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003493 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003494 mDone.set(true);
3495 mDone.notifyAll();
3496 }
3497 }
3498 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003499
3500 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3501 final AtomicBoolean mDone = new AtomicBoolean();
3502 int mResult;
3503
3504 public void reset() {
3505 synchronized (mDone) {
3506 mDone.set(false);
3507 }
3508 }
3509
3510 public void waitForCompletion() {
3511 synchronized (mDone) {
3512 while (mDone.get() == false) {
3513 try {
3514 mDone.wait();
3515 } catch (InterruptedException e) { }
3516 }
3517 }
3518 }
3519
3520 @Override
3521 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3522 synchronized (mDone) {
3523 mResult = returnCode;
3524 mDone.set(true);
3525 mDone.notifyAll();
3526 }
3527 }
3528 }
3529
Christopher Tate75a99702011-05-18 16:28:19 -07003530 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003531 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003532
3533 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3534 boolean okay = true;
3535
3536 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3537
3538 // The file content is an .apk file. Copy it out to a staging location and
3539 // attempt to install it.
3540 File apkFile = new File(mDataDir, info.packageName);
3541 try {
3542 FileOutputStream apkStream = new FileOutputStream(apkFile);
3543 byte[] buffer = new byte[32 * 1024];
3544 long size = info.size;
3545 while (size > 0) {
3546 long toRead = (buffer.length < size) ? buffer.length : size;
3547 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003548 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003549 apkStream.write(buffer, 0, didRead);
3550 size -= didRead;
3551 }
3552 apkStream.close();
3553
3554 // make sure the installer can read it
3555 apkFile.setReadable(true, false);
3556
3557 // Now install it
3558 Uri packageUri = Uri.fromFile(apkFile);
3559 mInstallObserver.reset();
3560 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003561 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3562 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003563 mInstallObserver.waitForCompletion();
3564
3565 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3566 // The only time we continue to accept install of data even if the
3567 // apk install failed is if we had already determined that we could
3568 // accept the data regardless.
3569 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3570 okay = false;
3571 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003572 } else {
3573 // Okay, the install succeeded. Make sure it was the right app.
3574 boolean uninstall = false;
3575 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3576 Slog.w(TAG, "Restore stream claimed to include apk for "
3577 + info.packageName + " but apk was really "
3578 + mInstallObserver.mPackageName);
3579 // delete the package we just put in place; it might be fraudulent
3580 okay = false;
3581 uninstall = true;
3582 } else {
3583 try {
3584 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3585 PackageManager.GET_SIGNATURES);
3586 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3587 Slog.w(TAG, "Restore stream contains apk of package "
3588 + info.packageName + " but it disallows backup/restore");
3589 okay = false;
3590 } else {
3591 // So far so good -- do the signatures match the manifest?
3592 Signature[] sigs = mManifestSignatures.get(info.packageName);
3593 if (!signaturesMatch(sigs, pkg)) {
3594 Slog.w(TAG, "Installed app " + info.packageName
3595 + " signatures do not match restore manifest");
3596 okay = false;
3597 uninstall = true;
3598 }
3599 }
3600 } catch (NameNotFoundException e) {
3601 Slog.w(TAG, "Install of package " + info.packageName
3602 + " succeeded but now not found");
3603 okay = false;
3604 }
3605 }
3606
3607 // If we're not okay at this point, we need to delete the package
3608 // that we just installed.
3609 if (uninstall) {
3610 mDeleteObserver.reset();
3611 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3612 mDeleteObserver, 0);
3613 mDeleteObserver.waitForCompletion();
3614 }
Christopher Tate75a99702011-05-18 16:28:19 -07003615 }
3616 } catch (IOException e) {
3617 Slog.e(TAG, "Unable to transcribe restored apk for install");
3618 okay = false;
3619 } finally {
3620 apkFile.delete();
3621 }
3622
3623 return okay;
3624 }
3625
3626 // Given an actual file content size, consume the post-content padding mandated
3627 // by the tar format.
3628 void skipTarPadding(long size, InputStream instream) throws IOException {
3629 long partial = (size + 512) % 512;
3630 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003631 final int needed = 512 - (int)partial;
3632 byte[] buffer = new byte[needed];
3633 if (readExactly(instream, buffer, 0, needed) == needed) {
3634 mBytes += needed;
3635 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003636 }
3637 }
3638
3639 // Returns a policy constant; takes a buffer arg to reduce memory churn
3640 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3641 throws IOException {
3642 // Fail on suspiciously large manifest files
3643 if (info.size > 64 * 1024) {
3644 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3645 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003646
Christopher Tate75a99702011-05-18 16:28:19 -07003647 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003648 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3649 mBytes += info.size;
3650 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003651
3652 RestorePolicy policy = RestorePolicy.IGNORE;
3653 String[] str = new String[1];
3654 int offset = 0;
3655
3656 try {
3657 offset = extractLine(buffer, offset, str);
3658 int version = Integer.parseInt(str[0]);
3659 if (version == BACKUP_MANIFEST_VERSION) {
3660 offset = extractLine(buffer, offset, str);
3661 String manifestPackage = str[0];
3662 // TODO: handle <original-package>
3663 if (manifestPackage.equals(info.packageName)) {
3664 offset = extractLine(buffer, offset, str);
3665 version = Integer.parseInt(str[0]); // app version
3666 offset = extractLine(buffer, offset, str);
3667 int platformVersion = Integer.parseInt(str[0]);
3668 offset = extractLine(buffer, offset, str);
3669 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3670 offset = extractLine(buffer, offset, str);
3671 boolean hasApk = str[0].equals("1");
3672 offset = extractLine(buffer, offset, str);
3673 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003674 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003675 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003676 for (int i = 0; i < numSigs; i++) {
3677 offset = extractLine(buffer, offset, str);
3678 sigs[i] = new Signature(str[0]);
3679 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003680 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003681
3682 // Okay, got the manifest info we need...
3683 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003684 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3685 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003686 // Fall through to IGNORE if the app explicitly disallows backup
3687 final int flags = pkgInfo.applicationInfo.flags;
3688 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003689 // Restore system-uid-space packages only if they have
3690 // defined a custom backup agent
3691 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3692 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3693 // Verify signatures against any installed version; if they
3694 // don't match, then we fall though and ignore the data. The
3695 // signatureMatch() method explicitly ignores the signature
3696 // check for packages installed on the system partition, because
3697 // such packages are signed with the platform cert instead of
3698 // the app developer's cert, so they're different on every
3699 // device.
3700 if (signaturesMatch(sigs, pkgInfo)) {
3701 if (pkgInfo.versionCode >= version) {
3702 Slog.i(TAG, "Sig + version match; taking data");
3703 policy = RestorePolicy.ACCEPT;
3704 } else {
3705 // The data is from a newer version of the app than
3706 // is presently installed. That means we can only
3707 // use it if the matching apk is also supplied.
3708 Slog.d(TAG, "Data version " + version
3709 + " is newer than installed version "
3710 + pkgInfo.versionCode + " - requiring apk");
3711 policy = RestorePolicy.ACCEPT_IF_APK;
3712 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003713 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003714 Slog.w(TAG, "Restore manifest signatures do not match "
3715 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003716 }
Christopher Tate75a99702011-05-18 16:28:19 -07003717 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003718 Slog.w(TAG, "Package " + info.packageName
3719 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003720 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003721 } else {
3722 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3723 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003724 }
3725 } catch (NameNotFoundException e) {
3726 // Okay, the target app isn't installed. We can process
3727 // the restore properly only if the dataset provides the
3728 // apk file and we can successfully install it.
3729 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3730 + " not installed; requiring apk in dataset");
3731 policy = RestorePolicy.ACCEPT_IF_APK;
3732 }
3733
3734 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3735 Slog.i(TAG, "Cannot restore package " + info.packageName
3736 + " without the matching .apk");
3737 }
3738 } else {
3739 Slog.i(TAG, "Missing signature on backed-up package "
3740 + info.packageName);
3741 }
3742 } else {
3743 Slog.i(TAG, "Expected package " + info.packageName
3744 + " but restore manifest claims " + manifestPackage);
3745 }
3746 } else {
3747 Slog.i(TAG, "Unknown restore manifest version " + version
3748 + " for package " + info.packageName);
3749 }
3750 } catch (NumberFormatException e) {
3751 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003752 } catch (IllegalArgumentException e) {
3753 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003754 }
3755
3756 return policy;
3757 }
3758
3759 // Builds a line from a byte buffer starting at 'offset', and returns
3760 // the index of the next unconsumed data in the buffer.
3761 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3762 final int end = buffer.length;
3763 if (offset >= end) throw new IOException("Incomplete data");
3764
3765 int pos;
3766 for (pos = offset; pos < end; pos++) {
3767 byte c = buffer[pos];
3768 // at LF we declare end of line, and return the next char as the
3769 // starting point for the next time through
3770 if (c == '\n') {
3771 break;
3772 }
3773 }
3774 outStr[0] = new String(buffer, offset, pos - offset);
3775 pos++; // may be pointing an extra byte past the end but that's okay
3776 return pos;
3777 }
3778
3779 void dumpFileMetadata(FileMetadata info) {
3780 if (DEBUG) {
3781 StringBuilder b = new StringBuilder(128);
3782
3783 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003784 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003785 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3786 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3787 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3788 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3789 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3790 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3791 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3792 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3793 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3794 b.append(String.format(" %9d ", info.size));
3795
3796 Date stamp = new Date(info.mtime);
3797 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3798
3799 b.append(info.packageName);
3800 b.append(" :: ");
3801 b.append(info.domain);
3802 b.append(" :: ");
3803 b.append(info.path);
3804
3805 Slog.i(TAG, b.toString());
3806 }
3807 }
3808 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3809 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3810 byte[] block = new byte[512];
3811 FileMetadata info = null;
3812
3813 boolean gotHeader = readTarHeader(instream, block);
3814 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003815 try {
3816 // okay, presume we're okay, and extract the various metadata
3817 info = new FileMetadata();
3818 info.size = extractRadix(block, 124, 12, 8);
3819 info.mtime = extractRadix(block, 136, 12, 8);
3820 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003821
Christopher Tate2efd2db2011-07-19 16:32:49 -07003822 info.path = extractString(block, 345, 155); // prefix
3823 String path = extractString(block, 0, 100);
3824 if (path.length() > 0) {
3825 if (info.path.length() > 0) info.path += '/';
3826 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003827 }
Christopher Tate75a99702011-05-18 16:28:19 -07003828
Christopher Tate2efd2db2011-07-19 16:32:49 -07003829 // tar link indicator field: 1 byte at offset 156 in the header.
3830 int typeChar = block[156];
3831 if (typeChar == 'x') {
3832 // pax extended header, so we need to read that
3833 gotHeader = readPaxExtendedHeader(instream, info);
3834 if (gotHeader) {
3835 // and after a pax extended header comes another real header -- read
3836 // that to find the real file type
3837 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003838 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003839 if (!gotHeader) throw new IOException("Bad or missing pax header");
3840
3841 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003842 }
Christopher Tate75a99702011-05-18 16:28:19 -07003843
Christopher Tate2efd2db2011-07-19 16:32:49 -07003844 switch (typeChar) {
3845 case '0': info.type = BackupAgent.TYPE_FILE; break;
3846 case '5': {
3847 info.type = BackupAgent.TYPE_DIRECTORY;
3848 if (info.size != 0) {
3849 Slog.w(TAG, "Directory entry with nonzero size in header");
3850 info.size = 0;
3851 }
3852 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003853 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003854 case 0: {
3855 // presume EOF
3856 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3857 return null;
3858 }
3859 default: {
3860 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3861 throw new IOException("Unknown entity type " + typeChar);
3862 }
Christopher Tate75a99702011-05-18 16:28:19 -07003863 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003864
3865 // Parse out the path
3866 //
3867 // first: apps/shared/unrecognized
3868 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3869 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3870 // File in shared storage. !!! TODO: implement this.
3871 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003872 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003873 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3874 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3875 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3876 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3877 // App content! Parse out the package name and domain
3878
3879 // strip the apps/ prefix
3880 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3881
3882 // extract the package name
3883 int slash = info.path.indexOf('/');
3884 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3885 info.packageName = info.path.substring(0, slash);
3886 info.path = info.path.substring(slash+1);
3887
3888 // if it's a manifest we're done, otherwise parse out the domains
3889 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3890 slash = info.path.indexOf('/');
3891 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3892 info.domain = info.path.substring(0, slash);
3893 // validate that it's one of the domains we understand
3894 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3895 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3896 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3897 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3898 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3899 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3900 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3901 throw new IOException("Unrecognized domain " + info.domain);
3902 }
3903
3904 info.path = info.path.substring(slash + 1);
3905 }
3906 }
3907 } catch (IOException e) {
3908 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003909 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003910 HEXLOG(block);
3911 }
3912 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003913 }
3914 }
3915 return info;
3916 }
3917
Christopher Tate2efd2db2011-07-19 16:32:49 -07003918 private void HEXLOG(byte[] block) {
3919 int offset = 0;
3920 int todo = block.length;
3921 StringBuilder buf = new StringBuilder(64);
3922 while (todo > 0) {
3923 buf.append(String.format("%04x ", offset));
3924 int numThisLine = (todo > 16) ? 16 : todo;
3925 for (int i = 0; i < numThisLine; i++) {
3926 buf.append(String.format("%02x ", block[offset+i]));
3927 }
3928 Slog.i("hexdump", buf.toString());
3929 buf.setLength(0);
3930 todo -= numThisLine;
3931 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003932 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003933 }
3934
Christopher Tate6853fcf2011-08-10 17:52:21 -07003935 // Read exactly the given number of bytes into a buffer at the stated offset.
3936 // Returns false if EOF is encountered before the requested number of bytes
3937 // could be read.
3938 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3939 throws IOException {
3940 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3941
3942 int soFar = 0;
3943 while (soFar < size) {
3944 int nRead = in.read(buffer, offset + soFar, size - soFar);
3945 if (nRead <= 0) {
3946 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3947 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003948 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003949 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003950 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003951 return soFar;
3952 }
3953
3954 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3955 final int got = readExactly(instream, block, 0, 512);
3956 if (got == 0) return false; // Clean EOF
3957 if (got < 512) throw new IOException("Unable to read full block header");
3958 mBytes += 512;
3959 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003960 }
3961
3962 // overwrites 'info' fields based on the pax extended header
3963 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3964 throws IOException {
3965 // We should never see a pax extended header larger than this
3966 if (info.size > 32*1024) {
3967 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3968 + " - aborting");
3969 throw new IOException("Sanity failure: pax header size " + info.size);
3970 }
3971
3972 // read whole blocks, not just the content size
3973 int numBlocks = (int)((info.size + 511) >> 9);
3974 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003975 if (readExactly(instream, data, 0, data.length) < data.length) {
3976 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003977 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003978 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003979
3980 final int contentSize = (int) info.size;
3981 int offset = 0;
3982 do {
3983 // extract the line at 'offset'
3984 int eol = offset+1;
3985 while (eol < contentSize && data[eol] != ' ') eol++;
3986 if (eol >= contentSize) {
3987 // error: we just hit EOD looking for the end of the size field
3988 throw new IOException("Invalid pax data");
3989 }
3990 // eol points to the space between the count and the key
3991 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3992 int key = eol + 1; // start of key=value
3993 eol = offset + linelen - 1; // trailing LF
3994 int value;
3995 for (value = key+1; data[value] != '=' && value <= eol; value++);
3996 if (value > eol) {
3997 throw new IOException("Invalid pax declaration");
3998 }
3999
4000 // pax requires that key/value strings be in UTF-8
4001 String keyStr = new String(data, key, value-key, "UTF-8");
4002 // -1 to strip the trailing LF
4003 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4004
4005 if ("path".equals(keyStr)) {
4006 info.path = valStr;
4007 } else if ("size".equals(keyStr)) {
4008 info.size = Long.parseLong(valStr);
4009 } else {
4010 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4011 }
4012
4013 offset += linelen;
4014 } while (offset < contentSize);
4015
4016 return true;
4017 }
4018
4019 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4020 throws IOException {
4021 long value = 0;
4022 final int end = offset + maxChars;
4023 for (int i = offset; i < end; i++) {
4024 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004025 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004026 if (b == 0 || b == ' ') break;
4027 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004028 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004029 }
4030 value = radix * value + (b - '0');
4031 }
4032 return value;
4033 }
4034
4035 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4036 final int end = offset + maxChars;
4037 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004038 // tar string fields terminate early with a NUL
4039 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004040 return new String(data, offset, eos-offset, "US-ASCII");
4041 }
4042
4043 void sendStartRestore() {
4044 if (mObserver != null) {
4045 try {
4046 mObserver.onStartRestore();
4047 } catch (RemoteException e) {
4048 Slog.w(TAG, "full restore observer went away: startRestore");
4049 mObserver = null;
4050 }
4051 }
4052 }
4053
4054 void sendOnRestorePackage(String name) {
4055 if (mObserver != null) {
4056 try {
4057 // TODO: use a more user-friendly name string
4058 mObserver.onRestorePackage(name);
4059 } catch (RemoteException e) {
4060 Slog.w(TAG, "full restore observer went away: restorePackage");
4061 mObserver = null;
4062 }
4063 }
4064 }
4065
4066 void sendEndRestore() {
4067 if (mObserver != null) {
4068 try {
4069 mObserver.onEndRestore();
4070 } catch (RemoteException e) {
4071 Slog.w(TAG, "full restore observer went away: endRestore");
4072 mObserver = null;
4073 }
4074 }
4075 }
4076 }
4077
Christopher Tatedf01dea2009-06-09 20:45:02 -07004078 // ----- Restore handling -----
4079
Christopher Tate78dd4a72009-11-04 11:49:08 -08004080 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4081 // If the target resides on the system partition, we allow it to restore
4082 // data from the like-named package in a restore set even if the signatures
4083 // do not match. (Unlike general applications, those flashed to the system
4084 // partition will be signed with the device's platform certificate, so on
4085 // different phones the same system app will have different signatures.)
4086 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004087 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004088 return true;
4089 }
4090
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004091 // Allow unsigned apps, but not signed on one device and unsigned on the other
4092 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004093 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004094 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004095 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004096 if ((storedSigs == null || storedSigs.length == 0)
4097 && (deviceSigs == null || deviceSigs.length == 0)) {
4098 return true;
4099 }
4100 if (storedSigs == null || deviceSigs == null) {
4101 return false;
4102 }
4103
Christopher Tateabce4e82009-06-18 18:35:32 -07004104 // !!! TODO: this demands that every stored signature match one
4105 // that is present on device, and does not demand the converse.
4106 // Is this this right policy?
4107 int nStored = storedSigs.length;
4108 int nDevice = deviceSigs.length;
4109
4110 for (int i=0; i < nStored; i++) {
4111 boolean match = false;
4112 for (int j=0; j < nDevice; j++) {
4113 if (storedSigs[i].equals(deviceSigs[j])) {
4114 match = true;
4115 break;
4116 }
4117 }
4118 if (!match) {
4119 return false;
4120 }
4121 }
4122 return true;
4123 }
4124
Christopher Tate2982d062011-09-06 20:35:24 -07004125 enum RestoreState {
4126 INITIAL,
4127 DOWNLOAD_DATA,
4128 PM_METADATA,
4129 RUNNING_QUEUE,
4130 FINAL
4131 }
4132
4133 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004134 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004135 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004136 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004137 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004138 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004139 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004140 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004141 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004142 private long mStartRealtime;
4143 private PackageManagerBackupAgent mPmAgent;
4144 private List<PackageInfo> mAgentPackages;
4145 private ArrayList<PackageInfo> mRestorePackages;
4146 private RestoreState mCurrentState;
4147 private int mCount;
4148 private boolean mFinished;
4149 private int mStatus;
4150 private File mBackupDataName;
4151 private File mNewStateName;
4152 private File mSavedStateName;
4153 private ParcelFileDescriptor mBackupData;
4154 private ParcelFileDescriptor mNewState;
4155 private PackageInfo mCurrentPackage;
4156
Christopher Tatedf01dea2009-06-09 20:45:02 -07004157
Christopher Tate5cbbf562009-06-22 16:44:51 -07004158 class RestoreRequest {
4159 public PackageInfo app;
4160 public int storedAppVersion;
4161
4162 RestoreRequest(PackageInfo _app, int _version) {
4163 app = _app;
4164 storedAppVersion = _version;
4165 }
4166 }
4167
Christopher Tate44a27902010-01-27 17:15:49 -08004168 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004169 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004170 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004171 mCurrentState = RestoreState.INITIAL;
4172 mFinished = false;
4173 mPmAgent = null;
4174
Christopher Tatedf01dea2009-06-09 20:45:02 -07004175 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004176 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004177 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004178 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004179 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004180 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004181
Christopher Tate284f1bb2011-07-07 14:31:18 -07004182 if (filterSet != null) {
4183 mFilterSet = new HashSet<String>();
4184 for (String pkg : filterSet) {
4185 mFilterSet.add(pkg);
4186 }
4187 } else {
4188 mFilterSet = null;
4189 }
4190
Christopher Tate5cb400b2009-06-25 16:03:14 -07004191 try {
4192 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4193 } catch (RemoteException e) {
4194 // can't happen; the transport is local
4195 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004196 }
4197
Christopher Tate2982d062011-09-06 20:35:24 -07004198 // Execute one tick of whatever state machine the task implements
4199 @Override
4200 public void execute() {
4201 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4202 switch (mCurrentState) {
4203 case INITIAL:
4204 beginRestore();
4205 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004206
Christopher Tate2982d062011-09-06 20:35:24 -07004207 case DOWNLOAD_DATA:
4208 downloadRestoreData();
4209 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004210
Christopher Tate2982d062011-09-06 20:35:24 -07004211 case PM_METADATA:
4212 restorePmMetadata();
4213 break;
4214
4215 case RUNNING_QUEUE:
4216 restoreNextAgent();
4217 break;
4218
4219 case FINAL:
4220 if (!mFinished) finalizeRestore();
4221 else {
4222 Slog.e(TAG, "Duplicate finish");
4223 }
4224 mFinished = true;
4225 break;
4226 }
4227 }
4228
4229 // Initialize and set up for the PM metadata restore, which comes first
4230 void beginRestore() {
4231 // Don't account time doing the restore as inactivity of the app
4232 // that has opened a restore session.
4233 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4234
4235 // Assume error until we successfully init everything
4236 mStatus = BackupConstants.TRANSPORT_ERROR;
4237
Christopher Tatedf01dea2009-06-09 20:45:02 -07004238 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004239 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004240 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004241
Dan Egnorefe52642009-06-24 00:16:33 -07004242 // Get the list of all packages which have backup enabled.
4243 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004244 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004245 PackageInfo omPackage = new PackageInfo();
4246 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004247 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004248
Christopher Tate2982d062011-09-06 20:35:24 -07004249 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004250 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004251 // if there's a filter set, strip out anything that isn't
4252 // present before proceeding
4253 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004254 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4255 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004256 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004257 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004258 }
4259 }
Christopher Tate2982d062011-09-06 20:35:24 -07004260 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004261 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004262 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004263 Slog.i(TAG, " " + p);
4264 }
4265 }
4266 }
Christopher Tate2982d062011-09-06 20:35:24 -07004267 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004268 } else {
4269 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004270 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004271 }
Dan Egnorefe52642009-06-24 00:16:33 -07004272
Christopher Tate7d562ec2009-06-25 18:03:43 -07004273 // let the observer know that we're running
4274 if (mObserver != null) {
4275 try {
4276 // !!! TODO: get an actual count from the transport after
4277 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004278 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004279 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004280 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004281 mObserver = null;
4282 }
4283 }
Christopher Tate2982d062011-09-06 20:35:24 -07004284 } catch (RemoteException e) {
4285 // Something has gone catastrophically wrong with the transport
4286 Slog.e(TAG, "Error communicating with transport for restore");
4287 executeNextState(RestoreState.FINAL);
4288 return;
4289 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004290
Christopher Tate2982d062011-09-06 20:35:24 -07004291 mStatus = BackupConstants.TRANSPORT_OK;
4292 executeNextState(RestoreState.DOWNLOAD_DATA);
4293 }
4294
4295 void downloadRestoreData() {
4296 // Note that the download phase can be very time consuming, but we're executing
4297 // it inline here on the looper. This is "okay" because it is not calling out to
4298 // third party code; the transport is "trusted," and so we assume it is being a
4299 // good citizen and timing out etc when appropriate.
4300 //
4301 // TODO: when appropriate, move the download off the looper and rearrange the
4302 // error handling around that.
4303 try {
4304 mStatus = mTransport.startRestore(mToken,
4305 mRestorePackages.toArray(new PackageInfo[0]));
4306 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004307 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004308 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004309 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004310 return;
4311 }
Christopher Tate2982d062011-09-06 20:35:24 -07004312 } catch (RemoteException e) {
4313 Slog.e(TAG, "Error communicating with transport for restore");
4314 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4315 mStatus = BackupConstants.TRANSPORT_ERROR;
4316 executeNextState(RestoreState.FINAL);
4317 return;
4318 }
Dan Egnorefe52642009-06-24 00:16:33 -07004319
Christopher Tate2982d062011-09-06 20:35:24 -07004320 // Successful download of the data to be parceled out to the apps, so off we go.
4321 executeNextState(RestoreState.PM_METADATA);
4322 }
4323
4324 void restorePmMetadata() {
4325 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004326 String packageName = mTransport.nextRestorePackage();
4327 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004328 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004329 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004330 mStatus = BackupConstants.TRANSPORT_ERROR;
4331 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004332 return;
4333 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004334 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004335 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004336 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004337 mStatus = BackupConstants.TRANSPORT_OK;
4338 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004339 return;
4340 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004341 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004342 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004343 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004344 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004345 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004346 return;
4347 }
4348
4349 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004350 PackageInfo omPackage = new PackageInfo();
4351 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4352 mPmAgent = new PackageManagerBackupAgent(
4353 mPackageManager, mAgentPackages);
4354 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004355 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004356 // The PM agent called operationComplete() already, because our invocation
4357 // of it is process-local and therefore synchronous. That means that a
4358 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4359 // proceed with running the queue do we remove that pending message and
4360 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004361
Christopher Tate8c032472009-07-02 14:28:47 -07004362 // Verify that the backup set includes metadata. If not, we can't do
4363 // signature/version verification etc, so we simply do not proceed with
4364 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004365 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004366 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004367 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004368 "Package manager restore metadata missing");
4369 mStatus = BackupConstants.TRANSPORT_ERROR;
4370 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4371 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004372 return;
4373 }
Christopher Tate2982d062011-09-06 20:35:24 -07004374 } catch (RemoteException e) {
4375 Slog.e(TAG, "Error communicating with transport for restore");
4376 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4377 mStatus = BackupConstants.TRANSPORT_ERROR;
4378 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4379 executeNextState(RestoreState.FINAL);
4380 return;
4381 }
Christopher Tate8c032472009-07-02 14:28:47 -07004382
Christopher Tate2982d062011-09-06 20:35:24 -07004383 // Metadata is intact, so we can now run the restore queue. If we get here,
4384 // we have already enqueued the necessary next-step message on the looper.
4385 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004386
Christopher Tate2982d062011-09-06 20:35:24 -07004387 void restoreNextAgent() {
4388 try {
4389 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004390
Christopher Tate2982d062011-09-06 20:35:24 -07004391 if (packageName == null) {
4392 Slog.e(TAG, "Error getting next restore package");
4393 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4394 executeNextState(RestoreState.FINAL);
4395 return;
4396 } else if (packageName.equals("")) {
4397 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4398 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4399 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4400 executeNextState(RestoreState.FINAL);
4401 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004402 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004403
4404 if (mObserver != null) {
4405 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004406 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004407 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004408 Slog.d(TAG, "Restore observer died in onUpdate");
4409 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004410 }
4411 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004412
Christopher Tate2982d062011-09-06 20:35:24 -07004413 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4414 if (metaInfo == null) {
4415 Slog.e(TAG, "Missing metadata for " + packageName);
4416 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4417 "Package metadata missing");
4418 executeNextState(RestoreState.RUNNING_QUEUE);
4419 return;
Christopher Tate84725812010-02-04 15:52:40 -08004420 }
4421
Christopher Tate2982d062011-09-06 20:35:24 -07004422 PackageInfo packageInfo;
4423 try {
4424 int flags = PackageManager.GET_SIGNATURES;
4425 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4426 } catch (NameNotFoundException e) {
4427 Slog.e(TAG, "Invalid package restoring data", e);
4428 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4429 "Package missing on device");
4430 executeNextState(RestoreState.RUNNING_QUEUE);
4431 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004432 }
4433
Christopher Tatee7287a02012-09-07 18:32:12 -07004434 if (packageInfo.applicationInfo.backupAgentName == null
4435 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4436 if (DEBUG) {
4437 Slog.i(TAG, "Data exists for package " + packageName
4438 + " but app has no agent; skipping");
4439 }
4440 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4441 "Package has no agent");
4442 executeNextState(RestoreState.RUNNING_QUEUE);
4443 return;
4444 }
4445
Christopher Tate2982d062011-09-06 20:35:24 -07004446 if (metaInfo.versionCode > packageInfo.versionCode) {
4447 // Data is from a "newer" version of the app than we have currently
4448 // installed. If the app has not declared that it is prepared to
4449 // handle this case, we do not attempt the restore.
4450 if ((packageInfo.applicationInfo.flags
4451 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4452 String message = "Version " + metaInfo.versionCode
4453 + " > installed version " + packageInfo.versionCode;
4454 Slog.w(TAG, "Package " + packageName + ": " + message);
4455 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4456 packageName, message);
4457 executeNextState(RestoreState.RUNNING_QUEUE);
4458 return;
4459 } else {
4460 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4461 + " > installed " + packageInfo.versionCode
4462 + " but restoreAnyVersion");
4463 }
4464 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004465
Christopher Tate2982d062011-09-06 20:35:24 -07004466 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4467 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4468 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4469 "Signature mismatch");
4470 executeNextState(RestoreState.RUNNING_QUEUE);
4471 return;
4472 }
4473
4474 if (DEBUG) Slog.v(TAG, "Package " + packageName
4475 + " restore version [" + metaInfo.versionCode
4476 + "] is compatible with installed version ["
4477 + packageInfo.versionCode + "]");
4478
4479 // Then set up and bind the agent
4480 IBackupAgent agent = bindToAgentSynchronous(
4481 packageInfo.applicationInfo,
4482 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4483 if (agent == null) {
4484 Slog.w(TAG, "Can't find backup agent for " + packageName);
4485 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4486 "Restore agent missing");
4487 executeNextState(RestoreState.RUNNING_QUEUE);
4488 return;
4489 }
4490
4491 // And then finally start the restore on this agent
4492 try {
4493 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4494 ++mCount;
4495 } catch (Exception e) {
4496 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4497 agentErrorCleanup();
4498 executeNextState(RestoreState.RUNNING_QUEUE);
4499 }
4500 } catch (RemoteException e) {
4501 Slog.e(TAG, "Unable to fetch restore data from transport");
4502 mStatus = BackupConstants.TRANSPORT_ERROR;
4503 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004504 }
4505 }
4506
Christopher Tate2982d062011-09-06 20:35:24 -07004507 void finalizeRestore() {
4508 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4509
4510 try {
4511 mTransport.finishRestore();
4512 } catch (RemoteException e) {
4513 Slog.e(TAG, "Error finishing restore", e);
4514 }
4515
4516 if (mObserver != null) {
4517 try {
4518 mObserver.restoreFinished(mStatus);
4519 } catch (RemoteException e) {
4520 Slog.d(TAG, "Restore observer died at restoreFinished");
4521 }
4522 }
4523
4524 // If this was a restoreAll operation, record that this was our
4525 // ancestral dataset, as well as the set of apps that are possibly
4526 // restoreable from the dataset
4527 if (mTargetPackage == null && mPmAgent != null) {
4528 mAncestralPackages = mPmAgent.getRestoredPackages();
4529 mAncestralToken = mToken;
4530 writeRestoreTokens();
4531 }
4532
4533 // We must under all circumstances tell the Package Manager to
4534 // proceed with install notifications if it's waiting for us.
4535 if (mPmToken > 0) {
4536 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4537 try {
4538 mPackageManagerBinder.finishPackageInstall(mPmToken);
4539 } catch (RemoteException e) { /* can't happen */ }
4540 }
4541
4542 // Furthermore we need to reset the session timeout clock
4543 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4544 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4545 TIMEOUT_RESTORE_INTERVAL);
4546
4547 // done; we can finally release the wakelock
4548 Slog.i(TAG, "Restore complete.");
4549 mWakelock.release();
4550 }
4551
4552 // Call asynchronously into the app, passing it the restore data. The next step
4553 // after this is always a callback, either operationComplete() or handleTimeout().
4554 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004555 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004556 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004557 final String packageName = app.packageName;
4558
Christopher Tate2982d062011-09-06 20:35:24 -07004559 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004560
Christopher Tatec7b31e32009-06-10 15:49:30 -07004561 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004562 mBackupDataName = new File(mDataDir, packageName + ".restore");
4563 mNewStateName = new File(mStateDir, packageName + ".new");
4564 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004565
Christopher Tate4a627c72011-04-01 14:43:32 -07004566 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004567 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004568 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004569 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004570 ParcelFileDescriptor.MODE_READ_WRITE |
4571 ParcelFileDescriptor.MODE_CREATE |
4572 ParcelFileDescriptor.MODE_TRUNCATE);
4573
Christopher Tate2982d062011-09-06 20:35:24 -07004574 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004575 // Transport-level failure, so we wind everything up and
4576 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004577 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004578 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004579 mBackupData.close();
4580 mBackupDataName.delete();
4581 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004582 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004583 }
4584
4585 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004586 mBackupData.close();
4587 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004588 ParcelFileDescriptor.MODE_READ_ONLY);
4589
Christopher Tate2982d062011-09-06 20:35:24 -07004590 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004591 ParcelFileDescriptor.MODE_READ_WRITE |
4592 ParcelFileDescriptor.MODE_CREATE |
4593 ParcelFileDescriptor.MODE_TRUNCATE);
4594
Christopher Tate44a27902010-01-27 17:15:49 -08004595 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004596 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4597 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004598 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004599 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004600 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004601 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004602
Christopher Tate2982d062011-09-06 20:35:24 -07004603 // After a restore failure we go back to running the queue. If there
4604 // are no more packages to be restored that will be handled by the
4605 // next step.
4606 executeNextState(RestoreState.RUNNING_QUEUE);
4607 }
4608 }
Chris Tate249345b2010-10-29 12:57:04 -07004609
Christopher Tate2982d062011-09-06 20:35:24 -07004610 void agentErrorCleanup() {
4611 // If the agent fails restore, it might have put the app's data
4612 // into an incoherent state. For consistency we wipe its data
4613 // again in this case before continuing with normal teardown
4614 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4615 agentCleanup();
4616 }
4617
4618 void agentCleanup() {
4619 mBackupDataName.delete();
4620 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4621 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4622 mBackupData = mNewState = null;
4623
4624 // if everything went okay, remember the recorded state now
4625 //
4626 // !!! TODO: the restored data should be migrated on the server
4627 // side into the current dataset. In that case the new state file
4628 // we just created would reflect the data already extant in the
4629 // backend, so there'd be nothing more to do. Until that happens,
4630 // however, we need to make sure that we record the data to the
4631 // current backend dataset. (Yes, this means shipping the data over
4632 // the wire in both directions. That's bad, but consistency comes
4633 // first, then efficiency.) Once we introduce server-side data
4634 // migration to the newly-restored device's dataset, we will change
4635 // the following from a discard of the newly-written state to the
4636 // "correct" operation of renaming into the canonical state blob.
4637 mNewStateName.delete(); // TODO: remove; see above comment
4638 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4639
4640 // If this wasn't the PM pseudopackage, tear down the agent side
4641 if (mCurrentPackage.applicationInfo != null) {
4642 // unbind and tidy up even on timeout or failure
4643 try {
4644 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4645
4646 // The agent was probably running with a stub Application object,
4647 // which isn't a valid run mode for the main app logic. Shut
4648 // down the app so that next time it's launched, it gets the
4649 // usual full initialization. Note that this is only done for
4650 // full-system restores: when a single app has requested a restore,
4651 // it is explicitly not killed following that operation.
4652 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4653 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4654 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4655 + mCurrentPackage.applicationInfo.processName);
4656 mActivityManager.killApplicationProcess(
4657 mCurrentPackage.applicationInfo.processName,
4658 mCurrentPackage.applicationInfo.uid);
4659 }
4660 } catch (RemoteException e) {
4661 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004662 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004663 }
Christopher Tate2982d062011-09-06 20:35:24 -07004664
4665 // The caller is responsible for reestablishing the state machine; our
4666 // responsibility here is to clear the decks for whatever comes next.
4667 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4668 synchronized (mCurrentOpLock) {
4669 mCurrentOperations.clear();
4670 }
4671 }
4672
4673 // A call to agent.doRestore() has been positively acknowledged as complete
4674 @Override
4675 public void operationComplete() {
4676 int size = (int) mBackupDataName.length();
4677 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4678 // Just go back to running the restore queue
4679 agentCleanup();
4680
4681 executeNextState(RestoreState.RUNNING_QUEUE);
4682 }
4683
4684 // A call to agent.doRestore() has timed out
4685 @Override
4686 public void handleTimeout() {
4687 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4688 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4689 mCurrentPackage.packageName, "restore timeout");
4690 // Handle like an agent that threw on invocation: wipe it and go on to the next
4691 agentErrorCleanup();
4692 executeNextState(RestoreState.RUNNING_QUEUE);
4693 }
4694
4695 void executeNextState(RestoreState nextState) {
4696 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4697 + this + " nextState=" + nextState);
4698 mCurrentState = nextState;
4699 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4700 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004701 }
4702 }
4703
Christopher Tate44a27902010-01-27 17:15:49 -08004704 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004705 IBackupTransport mTransport;
4706 PackageInfo mPackage;
4707
Christopher Tate44a27902010-01-27 17:15:49 -08004708 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004709 mTransport = transport;
4710 mPackage = packageInfo;
4711 }
4712
Christopher Tateee0e78a2009-07-02 11:17:03 -07004713 public void run() {
4714 try {
4715 // Clear the on-device backup state to ensure a full backup next time
4716 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4717 File stateFile = new File(stateDir, mPackage.packageName);
4718 stateFile.delete();
4719
4720 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004721 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004722 mTransport.clearBackupData(mPackage);
4723 } catch (RemoteException e) {
4724 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004725 } catch (Exception e) {
4726 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004727 } finally {
4728 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004729 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004730 mTransport.finishBackup();
4731 } catch (RemoteException e) {
4732 // can't happen; the transport is local
4733 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004734
4735 // Last but not least, release the cpu
4736 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004737 }
4738 }
4739 }
4740
Christopher Tate44a27902010-01-27 17:15:49 -08004741 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004742 HashSet<String> mQueue;
4743
Christopher Tate44a27902010-01-27 17:15:49 -08004744 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004745 mQueue = transportNames;
4746 }
4747
Christopher Tate4cc86e12009-09-21 19:36:51 -07004748 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004749 try {
4750 for (String transportName : mQueue) {
4751 IBackupTransport transport = getTransport(transportName);
4752 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004753 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004754 continue;
4755 }
4756
Joe Onorato8a9b2202010-02-26 18:56:32 -08004757 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004758 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004759 long startRealtime = SystemClock.elapsedRealtime();
4760 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004761
Christopher Tate4cc86e12009-09-21 19:36:51 -07004762 if (status == BackupConstants.TRANSPORT_OK) {
4763 status = transport.finishBackup();
4764 }
4765
4766 // Okay, the wipe really happened. Clean up our local bookkeeping.
4767 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004768 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004769 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004770 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004771 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004772 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004773 synchronized (mQueueLock) {
4774 recordInitPendingLocked(false, transportName);
4775 }
Dan Egnor726247c2009-09-29 19:12:31 -07004776 } else {
4777 // If this didn't work, requeue this one and try again
4778 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004779 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004780 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004781 synchronized (mQueueLock) {
4782 recordInitPendingLocked(true, transportName);
4783 }
4784 // do this via another alarm to make sure of the wakelock states
4785 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004786 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004787 + transportName + " resched in " + delay);
4788 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4789 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004790 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004791 }
4792 } catch (RemoteException e) {
4793 // can't happen; the transports are local
4794 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004795 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004796 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004797 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004798 mWakelock.release();
4799 }
4800 }
4801 }
4802
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004803 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004804 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004805 dataChangedImpl(packageName, targets);
4806 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004807
Christopher Tatea3d55342012-03-27 13:16:18 -07004808 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004809 // Record that we need a backup pass for the caller. Since multiple callers
4810 // may share a uid, we need to note all candidates within that uid and schedule
4811 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004812 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004813
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004814 if (targets == null) {
4815 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4816 + " uid=" + Binder.getCallingUid());
4817 return;
4818 }
4819
4820 synchronized (mQueueLock) {
4821 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004822 if (targets.contains(packageName)) {
4823 // Add the caller to the set of pending backups. If there is
4824 // one already there, then overwrite it, but no harm done.
4825 BackupRequest req = new BackupRequest(packageName);
4826 if (mPendingBackups.put(packageName, req) == null) {
4827 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004828
Christopher Tatea3d55342012-03-27 13:16:18 -07004829 // Journal this request in case of crash. The put()
4830 // operation returned null when this package was not already
4831 // in the set; we want to avoid touching the disk redundantly.
4832 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004833
Christopher Tatea3d55342012-03-27 13:16:18 -07004834 if (MORE_DEBUG) {
4835 int numKeys = mPendingBackups.size();
4836 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4837 for (BackupRequest b : mPendingBackups.values()) {
4838 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004839 }
4840 }
4841 }
4842 }
4843 }
4844 }
4845
4846 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004847 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004848 // If the caller does not hold the BACKUP permission, it can only request a
4849 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004850 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004851 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004852 synchronized (mBackupParticipants) {
4853 return mBackupParticipants.get(Binder.getCallingUid());
4854 }
4855 }
4856
4857 // a caller with full permission can ask to back up any participating app
4858 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004859 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004860 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004861 int N = mBackupParticipants.size();
4862 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004863 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004864 if (s != null) {
4865 targets.addAll(s);
4866 }
4867 }
4868 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004869 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004870 }
Christopher Tate46758122009-05-06 11:22:00 -07004871
Christopher Tatecde87f42009-06-12 12:55:53 -07004872 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004873 RandomAccessFile out = null;
4874 try {
4875 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4876 out = new RandomAccessFile(mJournal, "rws");
4877 out.seek(out.length());
4878 out.writeUTF(str);
4879 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004880 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004881 mJournal = null;
4882 } finally {
4883 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004884 }
4885 }
4886
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004887 // ----- IBackupManager binder interface -----
4888
4889 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004890 final int callingUserHandle = UserHandle.getCallingUserId();
4891 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004892 // App is running under a non-owner user profile. For now, we do not back
4893 // up data from secondary user profiles.
4894 // TODO: backups for all user profiles.
4895 if (MORE_DEBUG) {
4896 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4897 + callingUserHandle);
4898 }
4899 return;
4900 }
4901
Christopher Tatea3d55342012-03-27 13:16:18 -07004902 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004903 if (targets == null) {
4904 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4905 + " uid=" + Binder.getCallingUid());
4906 return;
4907 }
4908
4909 mBackupHandler.post(new Runnable() {
4910 public void run() {
4911 dataChangedImpl(packageName, targets);
4912 }
4913 });
4914 }
4915
Christopher Tateee0e78a2009-07-02 11:17:03 -07004916 // Clear the given package's backup data from the current transport
4917 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004918 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004919 PackageInfo info;
4920 try {
4921 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4922 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004923 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004924 return;
4925 }
4926
4927 // If the caller does not hold the BACKUP permission, it can only request a
4928 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004929 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004930 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004931 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4932 apps = mBackupParticipants.get(Binder.getCallingUid());
4933 } else {
4934 // a caller with full permission can ask to back up any participating app
4935 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004936 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004937 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004938 int N = mBackupParticipants.size();
4939 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004940 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004941 if (s != null) {
4942 apps.addAll(s);
4943 }
4944 }
4945 }
4946
Christopher Tatea3d55342012-03-27 13:16:18 -07004947 // Is the given app an available participant?
4948 if (apps.contains(packageName)) {
4949 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4950 // found it; fire off the clear request
4951 synchronized (mQueueLock) {
4952 long oldId = Binder.clearCallingIdentity();
4953 mWakelock.acquire();
4954 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4955 new ClearParams(getTransport(mCurrentTransport), info));
4956 mBackupHandler.sendMessage(msg);
4957 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004958 }
4959 }
4960 }
4961
Christopher Tateace7f092009-06-15 18:07:25 -07004962 // Run a backup pass immediately for any applications that have declared
4963 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004964 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004966
Joe Onorato8a9b2202010-02-26 18:56:32 -08004967 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004968 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004969 // Because the alarms we are using can jitter, and we want an *immediate*
4970 // backup pass to happen, we restart the timer beginning with "next time,"
4971 // then manually fire the backup trigger intent ourselves.
4972 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004973 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004974 mRunBackupIntent.send();
4975 } catch (PendingIntent.CanceledException e) {
4976 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004977 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004978 }
Christopher Tate46758122009-05-06 11:22:00 -07004979 }
4980 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004981
Christopher Tated2c0cd42011-09-15 15:51:29 -07004982 boolean deviceIsProvisioned() {
4983 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07004984 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004985 }
4986
Christopher Tate4a627c72011-04-01 14:43:32 -07004987 // Run a *full* backup pass for the given package, writing the resulting data stream
4988 // to the supplied file descriptor. This method is synchronous and does not return
4989 // to the caller until the backup has been completed.
4990 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004991 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004992 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4993
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004994 final int callingUserHandle = UserHandle.getCallingUserId();
4995 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004996 throw new IllegalStateException("Backup supported only for the device owner");
4997 }
4998
Christopher Tate4a627c72011-04-01 14:43:32 -07004999 // Validate
5000 if (!doAllApps) {
5001 if (!includeShared) {
5002 // If we're backing up shared data (sdcard or equivalent), then we can run
5003 // without any supplied app names. Otherwise, we'd be doing no work, so
5004 // report the error.
5005 if (pkgList == null || pkgList.length == 0) {
5006 throw new IllegalArgumentException(
5007 "Backup requested but neither shared nor any apps named");
5008 }
5009 }
5010 }
5011
Christopher Tate4a627c72011-04-01 14:43:32 -07005012 long oldId = Binder.clearCallingIdentity();
5013 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005014 // Doesn't make sense to do a full backup prior to setup
5015 if (!deviceIsProvisioned()) {
5016 Slog.i(TAG, "Full backup not supported before setup");
5017 return;
5018 }
5019
5020 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5021 + " shared=" + includeShared + " all=" + doAllApps
5022 + " pkgs=" + pkgList);
5023 Slog.i(TAG, "Beginning full backup...");
5024
Christopher Tate4a627c72011-04-01 14:43:32 -07005025 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005026 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005027 final int token = generateToken();
5028 synchronized (mFullConfirmations) {
5029 mFullConfirmations.put(token, params);
5030 }
5031
Christopher Tate75a99702011-05-18 16:28:19 -07005032 // start up the confirmation UI
5033 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5034 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5035 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005036 mFullConfirmations.delete(token);
5037 return;
5038 }
Christopher Tate75a99702011-05-18 16:28:19 -07005039
5040 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005041 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5042
5043 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005044 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005045
5046 // wait for the backup to be performed
5047 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5048 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005049 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005050 try {
5051 fd.close();
5052 } catch (IOException e) {
5053 // just eat it
5054 }
Christopher Tate75a99702011-05-18 16:28:19 -07005055 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005056 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005057 }
Christopher Tate75a99702011-05-18 16:28:19 -07005058 }
5059
5060 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005061 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005062
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005063 final int callingUserHandle = UserHandle.getCallingUserId();
5064 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005065 throw new IllegalStateException("Restore supported only for the device owner");
5066 }
5067
Christopher Tate75a99702011-05-18 16:28:19 -07005068 long oldId = Binder.clearCallingIdentity();
5069
5070 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005071 // Check whether the device has been provisioned -- we don't handle
5072 // full restores prior to completing the setup process.
5073 if (!deviceIsProvisioned()) {
5074 Slog.i(TAG, "Full restore not permitted before setup");
5075 return;
5076 }
5077
5078 Slog.i(TAG, "Beginning full restore...");
5079
Christopher Tate75a99702011-05-18 16:28:19 -07005080 FullRestoreParams params = new FullRestoreParams(fd);
5081 final int token = generateToken();
5082 synchronized (mFullConfirmations) {
5083 mFullConfirmations.put(token, params);
5084 }
5085
5086 // start up the confirmation UI
5087 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5088 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5089 Slog.e(TAG, "Unable to launch full restore confirmation");
5090 mFullConfirmations.delete(token);
5091 return;
5092 }
5093
5094 // make sure the screen is lit for the user interaction
5095 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5096
5097 // start the confirmation countdown
5098 startConfirmationTimeout(token, params);
5099
5100 // wait for the restore to be performed
5101 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5102 waitForCompletion(params);
5103 } finally {
5104 try {
5105 fd.close();
5106 } catch (IOException e) {
5107 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5108 }
5109 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005110 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005111 }
5112 }
5113
5114 boolean startConfirmationUi(int token, String action) {
5115 try {
5116 Intent confIntent = new Intent(action);
5117 confIntent.setClassName("com.android.backupconfirm",
5118 "com.android.backupconfirm.BackupRestoreConfirmation");
5119 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5120 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5121 mContext.startActivity(confIntent);
5122 } catch (ActivityNotFoundException e) {
5123 return false;
5124 }
5125 return true;
5126 }
5127
5128 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005129 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005130 + TIMEOUT_FULL_CONFIRMATION + " millis");
5131 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5132 token, 0, params);
5133 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005134 }
5135
5136 void waitForCompletion(FullParams params) {
5137 synchronized (params.latch) {
5138 while (params.latch.get() == false) {
5139 try {
5140 params.latch.wait();
5141 } catch (InterruptedException e) { /* never interrupted */ }
5142 }
5143 }
5144 }
5145
5146 void signalFullBackupRestoreCompletion(FullParams params) {
5147 synchronized (params.latch) {
5148 params.latch.set(true);
5149 params.latch.notifyAll();
5150 }
5151 }
5152
5153 // Confirm that the previously-requested full backup/restore operation can proceed. This
5154 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005155 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005156 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005157 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005158 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5159 + " allow=" + allow);
5160
5161 // TODO: possibly require not just this signature-only permission, but even
5162 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005163 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005164
5165 long oldId = Binder.clearCallingIdentity();
5166 try {
5167
5168 FullParams params;
5169 synchronized (mFullConfirmations) {
5170 params = mFullConfirmations.get(token);
5171 if (params != null) {
5172 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5173 mFullConfirmations.delete(token);
5174
5175 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005176 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005177 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005178 : MSG_RUN_FULL_RESTORE;
5179
Christopher Tate728a1c42011-07-28 18:03:03 -07005180 params.observer = observer;
5181 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005182
5183 boolean isEncrypted;
5184 try {
5185 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5186 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5187 } catch (RemoteException e) {
5188 // couldn't contact the mount service; fail "safe" and assume encryption
5189 Slog.e(TAG, "Unable to contact mount service!");
5190 isEncrypted = true;
5191 }
5192 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005193
Christopher Tate75a99702011-05-18 16:28:19 -07005194 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005195 mWakelock.acquire();
5196 Message msg = mBackupHandler.obtainMessage(verb, params);
5197 mBackupHandler.sendMessage(msg);
5198 } else {
5199 Slog.w(TAG, "User rejected full backup/restore operation");
5200 // indicate completion without having actually transferred any data
5201 signalFullBackupRestoreCompletion(params);
5202 }
5203 } else {
5204 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5205 }
5206 }
5207 } finally {
5208 Binder.restoreCallingIdentity(oldId);
5209 }
5210 }
5211
Christopher Tate8031a3d2009-07-06 16:36:05 -07005212 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005213 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005214 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005215 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005216
Joe Onorato8a9b2202010-02-26 18:56:32 -08005217 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005218
Christopher Tate6ef58a12009-06-29 14:56:28 -07005219 boolean wasEnabled = mEnabled;
5220 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005221 Settings.Secure.putInt(mContext.getContentResolver(),
5222 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005223 mEnabled = enable;
5224 }
5225
Christopher Tate49401dd2009-07-01 12:34:29 -07005226 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005227 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005228 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005229 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005230 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005231 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005232 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005233
Christopher Tateb6787f22009-07-02 17:40:45 -07005234 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005235
5236 // This also constitutes an opt-out, so we wipe any data for
5237 // this device from the backend. We start that process with
5238 // an alarm in order to guarantee wakelock states.
5239 if (wasEnabled && mProvisioned) {
5240 // NOTE: we currently flush every registered transport, not just
5241 // the currently-active one.
5242 HashSet<String> allTransports;
5243 synchronized (mTransports) {
5244 allTransports = new HashSet<String>(mTransports.keySet());
5245 }
5246 // build the set of transports for which we are posting an init
5247 for (String transport : allTransports) {
5248 recordInitPendingLocked(true, transport);
5249 }
5250 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5251 mRunInitIntent);
5252 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005253 }
5254 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005255 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005256
Christopher Tatecce9da52010-02-03 15:11:15 -08005257 // Enable/disable automatic restore of app data at install time
5258 public void setAutoRestore(boolean doAutoRestore) {
5259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005260 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005261
Joe Onorato8a9b2202010-02-26 18:56:32 -08005262 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005263
5264 synchronized (this) {
5265 Settings.Secure.putInt(mContext.getContentResolver(),
5266 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5267 mAutoRestore = doAutoRestore;
5268 }
5269 }
5270
Christopher Tate8031a3d2009-07-06 16:36:05 -07005271 // Mark the backup service as having been provisioned
5272 public void setBackupProvisioned(boolean available) {
5273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5274 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005275 /*
5276 * This is now a no-op; provisioning is simply the device's own setup state.
5277 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005278 }
5279
5280 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005281 // We used to use setInexactRepeating(), but that may be linked to
5282 // backups running at :00 more often than not, creating load spikes.
5283 // Schedule at an exact time for now, and also add a bit of "fuzz".
5284
5285 Random random = new Random();
5286 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5287 random.nextInt(FUZZ_MILLIS);
5288 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5289 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005290 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005291 }
5292
Christopher Tate6ef58a12009-06-29 14:56:28 -07005293 // Report whether the backup mechanism is currently enabled
5294 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005295 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005296 return mEnabled; // no need to synchronize just to read it
5297 }
5298
Christopher Tate91717492009-06-26 21:07:13 -07005299 // Report the name of the currently active transport
5300 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005301 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005302 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005303 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005304 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005305 }
5306
Christopher Tate91717492009-06-26 21:07:13 -07005307 // Report all known, available backup transports
5308 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005309 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005310
Christopher Tate91717492009-06-26 21:07:13 -07005311 String[] list = null;
5312 ArrayList<String> known = new ArrayList<String>();
5313 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5314 if (entry.getValue() != null) {
5315 known.add(entry.getKey());
5316 }
5317 }
5318
5319 if (known.size() > 0) {
5320 list = new String[known.size()];
5321 known.toArray(list);
5322 }
5323 return list;
5324 }
5325
5326 // Select which transport to use for the next backup operation. If the given
5327 // name is not one of the available transports, no action is taken and the method
5328 // returns null.
5329 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005330 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005331
5332 synchronized (mTransports) {
5333 String prevTransport = null;
5334 if (mTransports.get(transport) != null) {
5335 prevTransport = mCurrentTransport;
5336 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005337 Settings.Secure.putString(mContext.getContentResolver(),
5338 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005339 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005340 + " returning " + prevTransport);
5341 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005342 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005343 }
5344 return prevTransport;
5345 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005346 }
5347
Christopher Tatef5e1c292010-12-08 18:40:26 -08005348 // Supply the configuration Intent for the given transport. If the name is not one
5349 // of the available transports, or if the transport does not supply any configuration
5350 // UI, the method returns null.
5351 public Intent getConfigurationIntent(String transportName) {
5352 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5353 "getConfigurationIntent");
5354
5355 synchronized (mTransports) {
5356 final IBackupTransport transport = mTransports.get(transportName);
5357 if (transport != null) {
5358 try {
5359 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005360 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005361 + intent);
5362 return intent;
5363 } catch (RemoteException e) {
5364 /* fall through to return null */
5365 }
5366 }
5367 }
5368
5369 return null;
5370 }
5371
5372 // Supply the configuration summary string for the given transport. If the name is
5373 // not one of the available transports, or if the transport does not supply any
5374 // summary / destination string, the method can return null.
5375 //
5376 // This string is used VERBATIM as the summary text of the relevant Settings item!
5377 public String getDestinationString(String transportName) {
5378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005379 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005380
5381 synchronized (mTransports) {
5382 final IBackupTransport transport = mTransports.get(transportName);
5383 if (transport != null) {
5384 try {
5385 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005386 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005387 return text;
5388 } catch (RemoteException e) {
5389 /* fall through to return null */
5390 }
5391 }
5392 }
5393
5394 return null;
5395 }
5396
Christopher Tate043dadc2009-06-02 16:11:00 -07005397 // Callback: a requested backup agent has been instantiated. This should only
5398 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005399 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005400 synchronized(mAgentConnectLock) {
5401 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005403 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5404 mConnectedAgent = agent;
5405 mConnecting = false;
5406 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005407 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005408 + " claiming agent connected");
5409 }
5410 mAgentConnectLock.notifyAll();
5411 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005412 }
5413
5414 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5415 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005416 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005417 public void agentDisconnected(String packageName) {
5418 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005419 synchronized(mAgentConnectLock) {
5420 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5421 mConnectedAgent = null;
5422 mConnecting = false;
5423 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005424 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005425 + " claiming agent disconnected");
5426 }
5427 mAgentConnectLock.notifyAll();
5428 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005429 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005430
Christopher Tate1bb69062010-02-19 17:02:12 -08005431 // An application being installed will need a restore pass, then the Package Manager
5432 // will need to be told when the restore is finished.
5433 public void restoreAtInstall(String packageName, int token) {
5434 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005435 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005436 + " attemping install-time restore");
5437 return;
5438 }
5439
5440 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005441 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005442 + " token=" + Integer.toHexString(token)
5443 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005444
Christopher Tatef0872722010-02-25 15:22:48 -08005445 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005446 // okay, we're going to attempt a restore of this package from this restore set.
5447 // The eventual message back into the Package Manager to run the post-install
5448 // steps for 'token' will be issued from the restore handling code.
5449
5450 // We can use a synthetic PackageInfo here because:
5451 // 1. We know it's valid, since the Package Manager supplied the name
5452 // 2. Only the packageName field will be used by the restore code
5453 PackageInfo pkg = new PackageInfo();
5454 pkg.packageName = packageName;
5455
5456 mWakelock.acquire();
5457 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5458 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005459 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005460 mBackupHandler.sendMessage(msg);
5461 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005462 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5463 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005464 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005465 try {
5466 mPackageManagerBinder.finishPackageInstall(token);
5467 } catch (RemoteException e) { /* can't happen */ }
5468 }
5469 }
5470
Christopher Tate8c850b72009-06-07 19:33:20 -07005471 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005472 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5473 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5474 + " transport=" + transport);
5475
5476 boolean needPermission = true;
5477 if (transport == null) {
5478 transport = mCurrentTransport;
5479
5480 if (packageName != null) {
5481 PackageInfo app = null;
5482 try {
5483 app = mPackageManager.getPackageInfo(packageName, 0);
5484 } catch (NameNotFoundException nnf) {
5485 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5486 throw new IllegalArgumentException("Package " + packageName + " not found");
5487 }
5488
5489 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5490 // So: using the current active transport, and the caller has asked
5491 // that its own package will be restored. In this narrow use case
5492 // we do not require the caller to hold the permission.
5493 needPermission = false;
5494 }
5495 }
5496 }
5497
5498 if (needPermission) {
5499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5500 "beginRestoreSession");
5501 } else {
5502 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5503 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005504
5505 synchronized(this) {
5506 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005507 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005508 return null;
5509 }
Chris Tate44ab8452010-11-16 15:10:49 -08005510 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005511 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005512 }
5513 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005514 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005515
Christopher Tate73a3cb32010-12-13 18:27:26 -08005516 void clearRestoreSession(ActiveRestoreSession currentSession) {
5517 synchronized(this) {
5518 if (currentSession != mActiveRestoreSession) {
5519 Slog.e(TAG, "ending non-current restore session");
5520 } else {
5521 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5522 mActiveRestoreSession = null;
5523 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5524 }
5525 }
5526 }
5527
Christopher Tate44a27902010-01-27 17:15:49 -08005528 // Note that a currently-active backup agent has notified us that it has
5529 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005530 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005531 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005532 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5533 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005534 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005535 op = mCurrentOperations.get(token);
5536 if (op != null) {
5537 op.state = OP_ACKNOWLEDGED;
5538 }
Christopher Tate44a27902010-01-27 17:15:49 -08005539 mCurrentOpLock.notifyAll();
5540 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005541
5542 // The completion callback, if any, is invoked on the handler
5543 if (op != null && op.callback != null) {
5544 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5545 mBackupHandler.sendMessage(msg);
5546 }
Christopher Tate44a27902010-01-27 17:15:49 -08005547 }
5548
Christopher Tate9b3905c2009-06-08 15:24:01 -07005549 // ----- Restore session -----
5550
Christopher Tate80202c82010-01-25 19:37:47 -08005551 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005552 private static final String TAG = "RestoreSession";
5553
Chris Tate44ab8452010-11-16 15:10:49 -08005554 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005555 private IBackupTransport mRestoreTransport = null;
5556 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005557 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005558
Chris Tate44ab8452010-11-16 15:10:49 -08005559 ActiveRestoreSession(String packageName, String transport) {
5560 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005561 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005562 }
5563
5564 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005565 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005567 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005568 if (observer == null) {
5569 throw new IllegalArgumentException("Observer must not be null");
5570 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005571
Christopher Tate73a3cb32010-12-13 18:27:26 -08005572 if (mEnded) {
5573 throw new IllegalStateException("Restore session already ended");
5574 }
5575
Christopher Tate1bb69062010-02-19 17:02:12 -08005576 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005577 try {
Christopher Tate43383042009-07-13 15:17:13 -07005578 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005579 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005580 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005581 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005582 // spin off the transport request to our service thread
5583 mWakelock.acquire();
5584 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5585 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5586 mBackupHandler.sendMessage(msg);
5587 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005588 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005589 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005590 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005591 } finally {
5592 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005593 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005594 }
5595
Christopher Tate84725812010-02-04 15:52:40 -08005596 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005597 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5598 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005599
Chris Tate44ab8452010-11-16 15:10:49 -08005600 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005601 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005602
Christopher Tate73a3cb32010-12-13 18:27:26 -08005603 if (mEnded) {
5604 throw new IllegalStateException("Restore session already ended");
5605 }
5606
Dan Egnor0084da52009-07-29 12:57:16 -07005607 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005608 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5609 return -1;
5610 }
5611
5612 if (mPackageName != null) {
5613 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005614 return -1;
5615 }
5616
Christopher Tate21ab6a52009-09-24 18:01:46 -07005617 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005618 for (int i = 0; i < mRestoreSets.length; i++) {
5619 if (token == mRestoreSets[i].token) {
5620 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005621 mWakelock.acquire();
5622 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005623 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005624 mBackupHandler.sendMessage(msg);
5625 Binder.restoreCallingIdentity(oldId);
5626 return 0;
5627 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005628 }
5629 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005630
Joe Onorato8a9b2202010-02-26 18:56:32 -08005631 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005632 return -1;
5633 }
5634
Christopher Tate284f1bb2011-07-07 14:31:18 -07005635 public synchronized int restoreSome(long token, IRestoreObserver observer,
5636 String[] packages) {
5637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5638 "performRestore");
5639
5640 if (DEBUG) {
5641 StringBuilder b = new StringBuilder(128);
5642 b.append("restoreSome token=");
5643 b.append(Long.toHexString(token));
5644 b.append(" observer=");
5645 b.append(observer.toString());
5646 b.append(" packages=");
5647 if (packages == null) {
5648 b.append("null");
5649 } else {
5650 b.append('{');
5651 boolean first = true;
5652 for (String s : packages) {
5653 if (!first) {
5654 b.append(", ");
5655 } else first = false;
5656 b.append(s);
5657 }
5658 b.append('}');
5659 }
5660 Slog.d(TAG, b.toString());
5661 }
5662
5663 if (mEnded) {
5664 throw new IllegalStateException("Restore session already ended");
5665 }
5666
5667 if (mRestoreTransport == null || mRestoreSets == null) {
5668 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5669 return -1;
5670 }
5671
5672 if (mPackageName != null) {
5673 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5674 return -1;
5675 }
5676
5677 synchronized (mQueueLock) {
5678 for (int i = 0; i < mRestoreSets.length; i++) {
5679 if (token == mRestoreSets[i].token) {
5680 long oldId = Binder.clearCallingIdentity();
5681 mWakelock.acquire();
5682 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5683 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5684 packages, true);
5685 mBackupHandler.sendMessage(msg);
5686 Binder.restoreCallingIdentity(oldId);
5687 return 0;
5688 }
5689 }
5690 }
5691
5692 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5693 return -1;
5694 }
5695
Christopher Tate84725812010-02-04 15:52:40 -08005696 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005697 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005698
Christopher Tate73a3cb32010-12-13 18:27:26 -08005699 if (mEnded) {
5700 throw new IllegalStateException("Restore session already ended");
5701 }
5702
Chris Tate44ab8452010-11-16 15:10:49 -08005703 if (mPackageName != null) {
5704 if (! mPackageName.equals(packageName)) {
5705 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5706 + " on session for package " + mPackageName);
5707 return -1;
5708 }
5709 }
5710
Christopher Tate84725812010-02-04 15:52:40 -08005711 PackageInfo app = null;
5712 try {
5713 app = mPackageManager.getPackageInfo(packageName, 0);
5714 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005715 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005716 return -1;
5717 }
5718
5719 // If the caller is not privileged and is not coming from the target
5720 // app's uid, throw a permission exception back to the caller.
5721 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5722 Binder.getCallingPid(), Binder.getCallingUid());
5723 if ((perm == PackageManager.PERMISSION_DENIED) &&
5724 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005725 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005726 + " or calling uid=" + Binder.getCallingUid());
5727 throw new SecurityException("No permission to restore other packages");
5728 }
5729
Christopher Tate7d411a32010-02-26 11:27:08 -08005730 // If the package has no backup agent, we obviously cannot proceed
5731 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005732 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005733 return -1;
5734 }
5735
Christopher Tate84725812010-02-04 15:52:40 -08005736 // So far so good; we're allowed to try to restore this package. Now
5737 // check whether there is data for it in the current dataset, falling back
5738 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005739 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005740
5741 // If we didn't come up with a place to look -- no ancestral dataset and
5742 // the app has never been backed up from this device -- there's nothing
5743 // to do but return failure.
5744 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005745 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005746 return -1;
5747 }
5748
5749 // Ready to go: enqueue the restore request and claim success
5750 long oldId = Binder.clearCallingIdentity();
5751 mWakelock.acquire();
5752 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005753 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005754 mBackupHandler.sendMessage(msg);
5755 Binder.restoreCallingIdentity(oldId);
5756 return 0;
5757 }
5758
Christopher Tate73a3cb32010-12-13 18:27:26 -08005759 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5760 class EndRestoreRunnable implements Runnable {
5761 BackupManagerService mBackupManager;
5762 ActiveRestoreSession mSession;
5763
5764 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5765 mBackupManager = manager;
5766 mSession = session;
5767 }
5768
5769 public void run() {
5770 // clean up the session's bookkeeping
5771 synchronized (mSession) {
5772 try {
5773 if (mSession.mRestoreTransport != null) {
5774 mSession.mRestoreTransport.finishRestore();
5775 }
5776 } catch (Exception e) {
5777 Slog.e(TAG, "Error in finishRestore", e);
5778 } finally {
5779 mSession.mRestoreTransport = null;
5780 mSession.mEnded = true;
5781 }
5782 }
5783
5784 // clean up the BackupManagerService side of the bookkeeping
5785 // and cancel any pending timeout message
5786 mBackupManager.clearRestoreSession(mSession);
5787 }
5788 }
5789
Dan Egnor0084da52009-07-29 12:57:16 -07005790 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005791 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005792
Christopher Tate73a3cb32010-12-13 18:27:26 -08005793 if (mEnded) {
5794 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005795 }
5796
Christopher Tate73a3cb32010-12-13 18:27:26 -08005797 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005798 }
5799 }
5800
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005801 @Override
5802 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5804
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005805 long identityToken = Binder.clearCallingIdentity();
5806 try {
5807 dumpInternal(pw);
5808 } finally {
5809 Binder.restoreCallingIdentity(identityToken);
5810 }
5811 }
5812
5813 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005814 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005815 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005816 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005817 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005818 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005819 if (mBackupRunning) pw.println("Backup currently running");
5820 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005821 + " (now = " + System.currentTimeMillis() + ')');
5822 pw.println(" next scheduled: " + mNextBackupPass);
5823
Christopher Tate91717492009-06-26 21:07:13 -07005824 pw.println("Available transports:");
5825 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005826 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5827 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005828 IBackupTransport transport = getTransport(t);
5829 File dir = new File(mBaseStateDir, transport.transportDirName());
5830 pw.println(" destination: " + transport.currentDestinationString());
5831 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005832 for (File f : dir.listFiles()) {
5833 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5834 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005835 } catch (Exception e) {
5836 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005837 pw.println(" Error: " + e);
5838 }
Christopher Tate91717492009-06-26 21:07:13 -07005839 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005840
5841 pw.println("Pending init: " + mPendingInits.size());
5842 for (String s : mPendingInits) {
5843 pw.println(" " + s);
5844 }
5845
Christopher Tate6de74ff2012-01-17 15:20:32 -08005846 if (DEBUG_BACKUP_TRACE) {
5847 synchronized (mBackupTrace) {
5848 if (!mBackupTrace.isEmpty()) {
5849 pw.println("Most recent backup trace:");
5850 for (String s : mBackupTrace) {
5851 pw.println(" " + s);
5852 }
5853 }
5854 }
5855 }
5856
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005857 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005858 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005859 for (int i=0; i<N; i++) {
5860 int uid = mBackupParticipants.keyAt(i);
5861 pw.print(" uid: ");
5862 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005863 HashSet<String> participants = mBackupParticipants.valueAt(i);
5864 for (String app: participants) {
5865 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005866 }
5867 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005868
Christopher Tateb49ceb32010-02-08 16:22:24 -08005869 pw.println("Ancestral packages: "
5870 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005871 if (mAncestralPackages != null) {
5872 for (String pkg : mAncestralPackages) {
5873 pw.println(" " + pkg);
5874 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005875 }
5876
Christopher Tate73e02522009-07-15 14:18:26 -07005877 pw.println("Ever backed up: " + mEverStoredApps.size());
5878 for (String pkg : mEverStoredApps) {
5879 pw.println(" " + pkg);
5880 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005881
5882 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005883 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005884 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005885 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005886 }
5887 }
Christopher Tate487529a2009-04-29 14:03:25 -07005888}