blob: 401a25f4eba41f11374897a729e61e56b9518b1b [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 Tate559c6542013-02-12 14:57:04 -0800136 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);
Amith Yamasani27b89e62013-01-16 12:30:11 -0800839 context.bindServiceAsUser(intent, mGoogleConnection, Context.BIND_AUTO_CREATE,
840 UserHandle.OWNER);
Christopher Tatea32504f2010-04-21 17:58:07 -0700841 } else {
842 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
843 }
844 } catch (PackageManager.NameNotFoundException nnf) {
845 // No such package? No binding.
846 if (DEBUG) Slog.v(TAG, "Google transport not present");
847 }
Christopher Tateaa088442009-06-16 18:25:46 -0700848
Christopher Tatecde87f42009-06-12 12:55:53 -0700849 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700850 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700851 parseLeftoverJournals();
852
Christopher Tateb6787f22009-07-02 17:40:45 -0700853 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700854 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700855
856 // Start the backup passes going
857 setBackupEnabled(areEnabled);
858 }
859
860 private class RunBackupReceiver extends BroadcastReceiver {
861 public void onReceive(Context context, Intent intent) {
862 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700863 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700864 if (mPendingInits.size() > 0) {
865 // If there are pending init operations, we process those
866 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700868 try {
869 mAlarmManager.cancel(mRunInitIntent);
870 mRunInitIntent.send();
871 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700873 // can't really do more than bail here
874 }
875 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800876 // Don't run backups now if we're disabled or not yet
877 // fully set up.
878 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700879 if (!mBackupRunning) {
880 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700881
Christopher Tate336a6492011-10-05 16:05:43 -0700882 // Acquire the wakelock and pass it to the backup thread. it will
883 // be released once backup concludes.
884 mBackupRunning = true;
885 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700886
Christopher Tate336a6492011-10-05 16:05:43 -0700887 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
888 mBackupHandler.sendMessage(msg);
889 } else {
890 Slog.i(TAG, "Backup time but one already running");
891 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700892 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800893 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700894 }
895 }
896 }
897 }
898 }
899 }
900
901 private class RunInitializeReceiver extends BroadcastReceiver {
902 public void onReceive(Context context, Intent intent) {
903 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
904 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800905 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700906
907 // Acquire the wakelock and pass it to the init thread. it will
908 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700909 mWakelock.acquire();
910
Christopher Tate4cc86e12009-09-21 19:36:51 -0700911 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700912 mBackupHandler.sendMessage(msg);
913 }
914 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700915 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700916 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700917
Christopher Tate73e02522009-07-15 14:18:26 -0700918 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800919 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700920
Christopher Tate84725812010-02-04 15:52:40 -0800921 // Remember our ancestral dataset
922 mTokenFile = new File(mBaseStateDir, "ancestral");
923 try {
924 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800925 int version = tf.readInt();
926 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
927 mAncestralToken = tf.readLong();
928 mCurrentToken = tf.readLong();
929
930 int numPackages = tf.readInt();
931 if (numPackages >= 0) {
932 mAncestralPackages = new HashSet<String>();
933 for (int i = 0; i < numPackages; i++) {
934 String pkgName = tf.readUTF();
935 mAncestralPackages.add(pkgName);
936 }
937 }
938 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800939 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800940 } catch (FileNotFoundException fnf) {
941 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800942 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800943 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800944 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800945 }
946
Christopher Tatee97e8072009-07-15 16:45:50 -0700947 // Keep a log of what apps we've ever backed up. Because we might have
948 // rebooted in the middle of an operation that was removing something from
949 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700950 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700951 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700952
Christopher Tatee97e8072009-07-15 16:45:50 -0700953 // If we were in the middle of removing something from the ever-backed-up
954 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700955 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700956 if (tempProcessedFile.exists()) {
957 tempProcessedFile.delete();
958 }
959
Dan Egnor852f8e42009-09-30 11:20:45 -0700960 // If there are previous contents, parse them out then start a new
961 // file to continue the recordkeeping.
962 if (mEverStored.exists()) {
963 RandomAccessFile temp = null;
964 RandomAccessFile in = null;
965
966 try {
967 temp = new RandomAccessFile(tempProcessedFile, "rws");
968 in = new RandomAccessFile(mEverStored, "r");
969
970 while (true) {
971 PackageInfo info;
972 String pkg = in.readUTF();
973 try {
974 info = mPackageManager.getPackageInfo(pkg, 0);
975 mEverStoredApps.add(pkg);
976 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700977 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700978 } catch (NameNotFoundException e) {
979 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700980 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700981 }
982 }
983 } catch (EOFException e) {
984 // Once we've rewritten the backup history log, atomically replace the
985 // old one with the new one then reopen the file for continuing use.
986 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800987 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700988 }
989 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800990 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700991 } finally {
992 try { if (temp != null) temp.close(); } catch (IOException e) {}
993 try { if (in != null) in.close(); } catch (IOException e) {}
994 }
995 }
996
Christopher Tate73e02522009-07-15 14:18:26 -0700997 // Register for broadcasts about package install, etc., so we can
998 // update the provider list.
999 IntentFilter filter = new IntentFilter();
1000 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1001 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1002 filter.addDataScheme("package");
1003 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001004 // Register for events related to sdcard installation.
1005 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001006 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1007 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001008 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001009 }
1010
Christopher Tatecde87f42009-06-12 12:55:53 -07001011 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001012 for (File f : mJournalDir.listFiles()) {
1013 if (mJournal == null || f.compareTo(mJournal) != 0) {
1014 // This isn't the current journal, so it must be a leftover. Read
1015 // out the package names mentioned there and schedule them for
1016 // backup.
1017 RandomAccessFile in = null;
1018 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001019 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001020 in = new RandomAccessFile(f, "r");
1021 while (true) {
1022 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001023 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001024 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001025 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001026 } catch (EOFException e) {
1027 // no more data; we're done
1028 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001029 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001030 } finally {
1031 // close/delete the file
1032 try { if (in != null) in.close(); } catch (IOException e) {}
1033 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001034 }
1035 }
1036 }
1037 }
1038
Christopher Tate2efd2db2011-07-19 16:32:49 -07001039 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1040 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1041 }
1042
1043 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1044 try {
1045 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1046 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1047 return keyFactory.generateSecret(ks);
1048 } catch (InvalidKeySpecException e) {
1049 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1050 } catch (NoSuchAlgorithmException e) {
1051 Slog.e(TAG, "PBKDF2 unavailable!");
1052 }
1053 return null;
1054 }
1055
1056 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1057 SecretKey key = buildPasswordKey(pw, salt, rounds);
1058 if (key != null) {
1059 return byteArrayToHex(key.getEncoded());
1060 }
1061 return null;
1062 }
1063
1064 private String byteArrayToHex(byte[] data) {
1065 StringBuilder buf = new StringBuilder(data.length * 2);
1066 for (int i = 0; i < data.length; i++) {
1067 buf.append(Byte.toHexString(data[i], true));
1068 }
1069 return buf.toString();
1070 }
1071
1072 private byte[] hexToByteArray(String digits) {
1073 final int bytes = digits.length() / 2;
1074 if (2*bytes != digits.length()) {
1075 throw new IllegalArgumentException("Hex string must have an even number of digits");
1076 }
1077
1078 byte[] result = new byte[bytes];
1079 for (int i = 0; i < digits.length(); i += 2) {
1080 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1081 }
1082 return result;
1083 }
1084
1085 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1086 char[] mkAsChar = new char[pwBytes.length];
1087 for (int i = 0; i < pwBytes.length; i++) {
1088 mkAsChar[i] = (char) pwBytes[i];
1089 }
1090
1091 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1092 return checksum.getEncoded();
1093 }
1094
1095 // Used for generating random salts or passwords
1096 private byte[] randomBytes(int bits) {
1097 byte[] array = new byte[bits / 8];
1098 mRng.nextBytes(array);
1099 return array;
1100 }
1101
1102 // Backup password management
1103 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001104 // First, on an encrypted device we require matching the device pw
1105 final boolean isEncrypted;
1106 try {
1107 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1108 if (isEncrypted) {
1109 if (DEBUG) {
1110 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1111 }
1112 // 0 means the password validated
1113 // -2 means device not encrypted
1114 // Any other result is either password failure or an error condition,
1115 // so we refuse the match
1116 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1117 if (result == 0) {
1118 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1119 return true;
1120 } else if (result != -2) {
1121 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1122 return false;
1123 } else {
1124 // ...else the device is supposedly not encrypted. HOWEVER, the
1125 // query about the encryption state said that the device *is*
1126 // encrypted, so ... we may have a problem. Log it and refuse
1127 // the backup.
1128 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1129 return false;
1130 }
1131 }
1132 } catch (Exception e) {
1133 // Something went wrong talking to the mount service. This is very bad;
1134 // assume that we fail password validation.
1135 return false;
1136 }
1137
Christopher Tate2efd2db2011-07-19 16:32:49 -07001138 if (mPasswordHash == null) {
1139 // no current password case -- require that 'currentPw' be null or empty
1140 if (candidatePw == null || "".equals(candidatePw)) {
1141 return true;
1142 } // else the non-empty candidate does not match the empty stored pw
1143 } else {
1144 // hash the stated current pw and compare to the stored one
1145 if (candidatePw != null && candidatePw.length() > 0) {
1146 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1147 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1148 // candidate hash matches the stored hash -- the password matches
1149 return true;
1150 }
1151 } // else the stored pw is nonempty but the candidate is empty; no match
1152 }
1153 return false;
1154 }
1155
1156 @Override
1157 public boolean setBackupPassword(String currentPw, String newPw) {
1158 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1159 "setBackupPassword");
1160
1161 // If the supplied pw doesn't hash to the the saved one, fail
1162 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1163 return false;
1164 }
1165
1166 // Clearing the password is okay
1167 if (newPw == null || newPw.isEmpty()) {
1168 if (mPasswordHashFile.exists()) {
1169 if (!mPasswordHashFile.delete()) {
1170 // Unable to delete the old pw file, so fail
1171 Slog.e(TAG, "Unable to clear backup password");
1172 return false;
1173 }
1174 }
1175 mPasswordHash = null;
1176 mPasswordSalt = null;
1177 return true;
1178 }
1179
1180 try {
1181 // Okay, build the hash of the new backup password
1182 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1183 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1184
1185 OutputStream pwf = null, buffer = null;
1186 DataOutputStream out = null;
1187 try {
1188 pwf = new FileOutputStream(mPasswordHashFile);
1189 buffer = new BufferedOutputStream(pwf);
1190 out = new DataOutputStream(buffer);
1191 // integer length of the salt array, followed by the salt,
1192 // then the hex pw hash string
1193 out.writeInt(salt.length);
1194 out.write(salt);
1195 out.writeUTF(newPwHash);
1196 out.flush();
1197 mPasswordHash = newPwHash;
1198 mPasswordSalt = salt;
1199 return true;
1200 } finally {
1201 if (out != null) out.close();
1202 if (buffer != null) buffer.close();
1203 if (pwf != null) pwf.close();
1204 }
1205 } catch (IOException e) {
1206 Slog.e(TAG, "Unable to set backup password");
1207 }
1208 return false;
1209 }
1210
1211 @Override
1212 public boolean hasBackupPassword() {
1213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1214 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001215
1216 try {
1217 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1218 || (mPasswordHash != null && mPasswordHash.length() > 0);
1219 } catch (Exception e) {
1220 // If we can't talk to the mount service we have a serious problem; fail
1221 // "secure" i.e. assuming that we require a password
1222 return true;
1223 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001224 }
1225
Christopher Tate4cc86e12009-09-21 19:36:51 -07001226 // Maintain persistent state around whether need to do an initialize operation.
1227 // Must be called with the queue lock held.
1228 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001229 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001230 + " on transport " + transportName);
1231 try {
1232 IBackupTransport transport = getTransport(transportName);
1233 String transportDirName = transport.transportDirName();
1234 File stateDir = new File(mBaseStateDir, transportDirName);
1235 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1236
1237 if (isPending) {
1238 // We need an init before we can proceed with sending backup data.
1239 // Record that with an entry in our set of pending inits, as well as
1240 // journaling it via creation of a sentinel file.
1241 mPendingInits.add(transportName);
1242 try {
1243 (new FileOutputStream(initPendingFile)).close();
1244 } catch (IOException ioe) {
1245 // Something is badly wrong with our permissions; just try to move on
1246 }
1247 } else {
1248 // No more initialization needed; wipe the journal and reset our state.
1249 initPendingFile.delete();
1250 mPendingInits.remove(transportName);
1251 }
1252 } catch (RemoteException e) {
1253 // can't happen; the transport is local
1254 }
1255 }
1256
Christopher Tated55e18a2009-09-21 10:12:59 -07001257 // Reset all of our bookkeeping, in response to having been told that
1258 // the backend data has been wiped [due to idle expiry, for example],
1259 // so we must re-upload all saved settings.
1260 void resetBackupState(File stateFileDir) {
1261 synchronized (mQueueLock) {
1262 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001263 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001264 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001265
Christopher Tate84725812010-02-04 15:52:40 -08001266 mCurrentToken = 0;
1267 writeRestoreTokens();
1268
Christopher Tated55e18a2009-09-21 10:12:59 -07001269 // Remove all the state files
1270 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001271 // ... but don't touch the needs-init sentinel
1272 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1273 sf.delete();
1274 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001275 }
Christopher Tate45597642011-04-04 16:59:21 -07001276 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001277
Christopher Tate45597642011-04-04 16:59:21 -07001278 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001279 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001280 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001281 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001282 HashSet<String> participants = mBackupParticipants.valueAt(i);
1283 if (participants != null) {
1284 for (String packageName : participants) {
1285 dataChangedImpl(packageName);
1286 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001287 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001288 }
1289 }
1290 }
1291
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001292 // Add a transport to our set of available backends. If 'transport' is null, this
1293 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001294 private void registerTransport(String name, IBackupTransport transport) {
1295 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001296 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001297 if (transport != null) {
1298 mTransports.put(name, transport);
1299 } else {
1300 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001301 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001302 mCurrentTransport = null;
1303 }
1304 // Nothing further to do in the unregistration case
1305 return;
1306 }
Christopher Tate91717492009-06-26 21:07:13 -07001307 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001308
1309 // If the init sentinel file exists, we need to be sure to perform the init
1310 // as soon as practical. We also create the state directory at registration
1311 // time to ensure it's present from the outset.
1312 try {
1313 String transportName = transport.transportDirName();
1314 File stateDir = new File(mBaseStateDir, transportName);
1315 stateDir.mkdirs();
1316
1317 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1318 if (initSentinel.exists()) {
1319 synchronized (mQueueLock) {
1320 mPendingInits.add(transportName);
1321
1322 // TODO: pick a better starting time than now + 1 minute
1323 long delay = 1000 * 60; // one minute, in milliseconds
1324 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1325 System.currentTimeMillis() + delay, mRunInitIntent);
1326 }
1327 }
1328 } catch (RemoteException e) {
1329 // can't happen, the transport is local
1330 }
Christopher Tate91717492009-06-26 21:07:13 -07001331 }
1332
Christopher Tate3799bc22009-05-06 16:13:56 -07001333 // ----- Track installation/removal of packages -----
1334 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1335 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001336 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001337
Christopher Tate3799bc22009-05-06 16:13:56 -07001338 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001339 boolean replacing = false;
1340 boolean added = false;
1341 Bundle extras = intent.getExtras();
1342 String pkgList[] = null;
1343 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001344 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001345 Uri uri = intent.getData();
1346 if (uri == null) {
1347 return;
1348 }
1349 String pkgName = uri.getSchemeSpecificPart();
1350 if (pkgName != null) {
1351 pkgList = new String[] { pkgName };
1352 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001353 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1354 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001355 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001356 added = true;
1357 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001358 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001359 added = false;
1360 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1361 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001362
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001363 if (pkgList == null || pkgList.length == 0) {
1364 return;
1365 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001366
1367 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001368 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001369 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001370 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001371 // This is the package-replaced case; we just remove the entry
1372 // under the old uid and fall through to re-add.
1373 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001374 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001375 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001376 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001377 } else {
1378 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001379 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1380 } else {
1381 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001382 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 }
1384 }
1385 }
1386 }
1387 };
1388
Dan Egnor87a02bc2009-06-17 02:30:10 -07001389 // ----- Track connection to GoogleBackupTransport service -----
1390 ServiceConnection mGoogleConnection = new ServiceConnection() {
1391 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001392 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001393 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001394 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001395 }
1396
1397 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001398 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001399 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001400 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001401 }
1402 };
1403
Christopher Tate0bacfd22012-01-11 14:41:19 -08001404 // Add the backup agents in the given packages to our set of known backup participants.
1405 // If 'packageNames' is null, adds all backup agents in the whole system.
1406 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001407 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001408 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001409 if (packageNames != null) {
1410 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1411 for (String packageName : packageNames) {
1412 addPackageParticipantsLockedInner(packageName, targetApps);
1413 }
1414 } else {
1415 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1416 addPackageParticipantsLockedInner(null, targetApps);
1417 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001418 }
1419
Christopher Tate181fafa2009-05-14 11:12:14 -07001420 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001421 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001422 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001423 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001424 }
1425
Dan Egnorefe52642009-06-24 00:16:33 -07001426 for (PackageInfo pkg : targetPkgs) {
1427 if (packageName == null || pkg.packageName.equals(packageName)) {
1428 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001429 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001430 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001431 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001432 mBackupParticipants.put(uid, set);
1433 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001434 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001435 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001436
Christopher Tatee82f68d2012-10-23 15:07:38 -07001437 // Schedule a backup for it on general principles
1438 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1439 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001440 }
Christopher Tate487529a2009-04-29 14:03:25 -07001441 }
1442 }
1443
Christopher Tate0bacfd22012-01-11 14:41:19 -08001444 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001445 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001446 if (packageNames == null) {
1447 Slog.w(TAG, "removePackageParticipants with null list");
1448 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001449 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001450
Christopher Tatea3d55342012-03-27 13:16:18 -07001451 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1452 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001453 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001454 // Known previous UID, so we know which package set to check
1455 HashSet<String> set = mBackupParticipants.get(oldUid);
1456 if (set != null && set.contains(pkg)) {
1457 removePackageFromSetLocked(set, pkg);
1458 if (set.isEmpty()) {
1459 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1460 mBackupParticipants.remove(oldUid);
1461 }
1462 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001463 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001464 }
1465
Christopher Tatea3d55342012-03-27 13:16:18 -07001466 private void removePackageFromSetLocked(final HashSet<String> set,
1467 final String packageName) {
1468 if (set.contains(packageName)) {
1469 // Found it. Remove this one package from the bookkeeping, and
1470 // if it's the last participating app under this uid we drop the
1471 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001472 // Note that we deliberately leave it 'known' in the "ever backed up"
1473 // bookkeeping so that its current-dataset data will be retrieved
1474 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001475 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001476 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001477 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001478 }
1479 }
1480
Christopher Tate181fafa2009-05-14 11:12:14 -07001481 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001482 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001483 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001484 int flags = PackageManager.GET_SIGNATURES;
1485 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1486 int N = packages.size();
1487 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001488 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001489 try {
1490 ApplicationInfo app = pkg.applicationInfo;
1491 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001492 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001493 packages.remove(a);
1494 }
1495 else {
1496 // we will need the shared library path, so look that up and store it here
1497 app = mPackageManager.getApplicationInfo(pkg.packageName,
1498 PackageManager.GET_SHARED_LIBRARY_FILES);
1499 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1500 }
1501 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001502 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001503 }
1504 }
Dan Egnorefe52642009-06-24 00:16:33 -07001505 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001506 }
Christopher Tateaa088442009-06-16 18:25:46 -07001507
Christopher Tate84725812010-02-04 15:52:40 -08001508 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001509 // backed up at least once
1510 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001511 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1512
1513 synchronized (mEverStoredApps) {
1514 if (!mEverStoredApps.add(packageName)) return;
1515
1516 RandomAccessFile out = null;
1517 try {
1518 out = new RandomAccessFile(mEverStored, "rws");
1519 out.seek(out.length());
1520 out.writeUTF(packageName);
1521 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001523 } finally {
1524 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001525 }
1526 }
1527 }
1528
Christopher Tatee97e8072009-07-15 16:45:50 -07001529 // Remove our awareness of having ever backed up the given package
1530 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001531 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1532 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001533
Dan Egnor852f8e42009-09-30 11:20:45 -07001534 synchronized (mEverStoredApps) {
1535 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1536 // we'll recognize on initialization time that the package no longer
1537 // exists and fix it up then.
1538 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1539 RandomAccessFile known = null;
1540 try {
1541 known = new RandomAccessFile(tempKnownFile, "rws");
1542 mEverStoredApps.remove(packageName);
1543 for (String s : mEverStoredApps) {
1544 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001545 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001546 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001547 known.close();
1548 known = null;
1549 if (!tempKnownFile.renameTo(mEverStored)) {
1550 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1551 }
1552 } catch (IOException e) {
1553 // Bad: we couldn't create the new copy. For safety's sake we
1554 // abandon the whole process and remove all what's-backed-up
1555 // state entirely, meaning we'll force a backup pass for every
1556 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001558 mEverStoredApps.clear();
1559 tempKnownFile.delete();
1560 mEverStored.delete();
1561 } finally {
1562 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001563 }
1564 }
1565 }
1566
Christopher Tateb49ceb32010-02-08 16:22:24 -08001567 // Persistently record the current and ancestral backup tokens as well
1568 // as the set of packages with data [supposedly] available in the
1569 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001570 void writeRestoreTokens() {
1571 try {
1572 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001573
1574 // First, the version number of this record, for futureproofing
1575 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1576
1577 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001578 af.writeLong(mAncestralToken);
1579 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001580
1581 // Now write the set of ancestral packages
1582 if (mAncestralPackages == null) {
1583 af.writeInt(-1);
1584 } else {
1585 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001587 for (String pkgName : mAncestralPackages) {
1588 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001589 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001590 }
1591 }
Christopher Tate84725812010-02-04 15:52:40 -08001592 af.close();
1593 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001595 }
1596 }
1597
Dan Egnor87a02bc2009-06-17 02:30:10 -07001598 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001599 private IBackupTransport getTransport(String transportName) {
1600 synchronized (mTransports) {
1601 IBackupTransport transport = mTransports.get(transportName);
1602 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001603 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001604 }
1605 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001606 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001607 }
1608
Christopher Tatedf01dea2009-06-09 20:45:02 -07001609 // fire off a backup agent, blocking until it attaches or times out
1610 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1611 IBackupAgent agent = null;
1612 synchronized(mAgentConnectLock) {
1613 mConnecting = true;
1614 mConnectedAgent = null;
1615 try {
1616 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001618
1619 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001620 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001621 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1622 while (mConnecting && mConnectedAgent == null
1623 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001624 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001626 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001627 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001628 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001629 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001630 return null;
1631 }
1632 }
1633
1634 // if we timed out with no connect, abort and move on
1635 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001637 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 return null;
1639 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001640 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001641 agent = mConnectedAgent;
1642 }
1643 } catch (RemoteException e) {
1644 // can't happen
1645 }
1646 }
1647 return agent;
1648 }
1649
Christopher Tatec7b31e32009-06-10 15:49:30 -07001650 // clear an application's data, blocking until the operation completes or times out
1651 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001652 // Don't wipe packages marked allowClearUserData=false
1653 try {
1654 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1655 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001656 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001657 + packageName);
1658 return;
1659 }
1660 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001662 return;
1663 }
1664
Christopher Tatec7b31e32009-06-10 15:49:30 -07001665 ClearDataObserver observer = new ClearDataObserver();
1666
1667 synchronized(mClearDataLock) {
1668 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001669 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001670 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001671 } catch (RemoteException e) {
1672 // can't happen because the activity manager is in this process
1673 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001674
1675 // only wait 10 seconds for the clear data to happen
1676 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1677 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1678 try {
1679 mClearDataLock.wait(5000);
1680 } catch (InterruptedException e) {
1681 // won't happen, but still.
1682 mClearingData = false;
1683 }
1684 }
1685 }
1686 }
1687
1688 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001689 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001690 synchronized(mClearDataLock) {
1691 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001692 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001693 }
1694 }
1695 }
1696
Christopher Tate1bb69062010-02-19 17:02:12 -08001697 // Get the restore-set token for the best-available restore set for this package:
1698 // the active set if possible, else the ancestral one. Returns zero if none available.
1699 long getAvailableRestoreToken(String packageName) {
1700 long token = mAncestralToken;
1701 synchronized (mQueueLock) {
1702 if (mEverStoredApps.contains(packageName)) {
1703 token = mCurrentToken;
1704 }
1705 }
1706 return token;
1707 }
1708
Christopher Tate44a27902010-01-27 17:15:49 -08001709 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001710 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1711
1712 interface BackupRestoreTask {
1713 // Execute one tick of whatever state machine the task implements
1714 void execute();
1715
1716 // An operation that wanted a callback has completed
1717 void operationComplete();
1718
1719 // An operation that wanted a callback has timed out
1720 void handleTimeout();
1721 }
1722
1723 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1724 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1725 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001726 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001727 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1728
1729 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1730 mBackupHandler.sendMessageDelayed(msg, interval);
1731 }
1732 }
1733
1734 // synchronous waiter case
1735 boolean waitUntilOperationComplete(int token) {
1736 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1737 + Integer.toHexString(token));
1738 int finalState = OP_PENDING;
1739 Operation op = null;
1740 synchronized (mCurrentOpLock) {
1741 while (true) {
1742 op = mCurrentOperations.get(token);
1743 if (op == null) {
1744 // mysterious disappearance: treat as success with no callback
1745 break;
1746 } else {
1747 if (op.state == OP_PENDING) {
1748 try {
1749 mCurrentOpLock.wait();
1750 } catch (InterruptedException e) {}
1751 // When the wait is notified we loop around and recheck the current state
1752 } else {
1753 // No longer pending; we're done
1754 finalState = op.state;
1755 break;
1756 }
Christopher Tate44a27902010-01-27 17:15:49 -08001757 }
Christopher Tate44a27902010-01-27 17:15:49 -08001758 }
1759 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001760
Christopher Tate44a27902010-01-27 17:15:49 -08001761 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001762 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001763 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001764 return finalState == OP_ACKNOWLEDGED;
1765 }
1766
Christopher Tate8e294d42011-08-31 20:37:12 -07001767 void handleTimeout(int token, Object obj) {
1768 // Notify any synchronous waiters
1769 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001770 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001771 op = mCurrentOperations.get(token);
1772 if (MORE_DEBUG) {
1773 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1774 + " but no op found");
1775 }
1776 int state = (op != null) ? op.state : OP_TIMEOUT;
1777 if (state == OP_PENDING) {
1778 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1779 op.state = OP_TIMEOUT;
1780 mCurrentOperations.put(token, op);
1781 }
1782 mCurrentOpLock.notifyAll();
1783 }
1784
1785 // If there's a TimeoutHandler for this event, call it
1786 if (op != null && op.callback != null) {
1787 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001788 }
Christopher Tate44a27902010-01-27 17:15:49 -08001789 }
1790
Christopher Tate043dadc2009-06-02 16:11:00 -07001791 // ----- Back up a set of applications via a worker thread -----
1792
Christopher Tate8e294d42011-08-31 20:37:12 -07001793 enum BackupState {
1794 INITIAL,
1795 RUNNING_QUEUE,
1796 FINAL
1797 }
1798
1799 class PerformBackupTask implements BackupRestoreTask {
1800 private static final String TAG = "PerformBackupTask";
1801
Christopher Tateaa088442009-06-16 18:25:46 -07001802 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001803 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001804 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001805 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001806 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001807 BackupState mCurrentState;
1808
1809 // carried information about the current in-flight operation
1810 PackageInfo mCurrentPackage;
1811 File mSavedStateName;
1812 File mBackupDataName;
1813 File mNewStateName;
1814 ParcelFileDescriptor mSavedState;
1815 ParcelFileDescriptor mBackupData;
1816 ParcelFileDescriptor mNewState;
1817 int mStatus;
1818 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001819
Christopher Tate44a27902010-01-27 17:15:49 -08001820 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001821 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001822 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001823 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001824 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001825
1826 try {
1827 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1828 } catch (RemoteException e) {
1829 // can't happen; the transport is local
1830 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001831
1832 mCurrentState = BackupState.INITIAL;
1833 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001834
1835 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001836 }
1837
Christopher Tate8e294d42011-08-31 20:37:12 -07001838 // Main entry point: perform one chunk of work, updating the state as appropriate
1839 // and reposting the next chunk to the primary backup handler thread.
1840 @Override
1841 public void execute() {
1842 switch (mCurrentState) {
1843 case INITIAL:
1844 beginBackup();
1845 break;
1846
1847 case RUNNING_QUEUE:
1848 invokeNextAgent();
1849 break;
1850
1851 case FINAL:
1852 if (!mFinished) finalizeBackup();
1853 else {
1854 Slog.e(TAG, "Duplicate finish");
1855 }
Christopher Tate2982d062011-09-06 20:35:24 -07001856 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001857 break;
1858 }
1859 }
1860
1861 // We're starting a backup pass. Initialize the transport and send
1862 // the PM metadata blob if we haven't already.
1863 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001864 if (DEBUG_BACKUP_TRACE) {
1865 clearBackupTrace();
1866 StringBuilder b = new StringBuilder(256);
1867 b.append("beginBackup: [");
1868 for (BackupRequest req : mOriginalQueue) {
1869 b.append(' ');
1870 b.append(req.packageName);
1871 }
1872 b.append(" ]");
1873 addBackupTrace(b.toString());
1874 }
1875
Christopher Tate8e294d42011-08-31 20:37:12 -07001876 mStatus = BackupConstants.TRANSPORT_OK;
1877
1878 // Sanity check: if the queue is empty we have no work to do.
1879 if (mOriginalQueue.isEmpty()) {
1880 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001881 addBackupTrace("queue empty at begin");
1882 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001883 return;
1884 }
1885
1886 // We need to retain the original queue contents in case of transport
1887 // failure, but we want a working copy that we can manipulate along
1888 // the way.
1889 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1890
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001892
Christopher Tate8e294d42011-08-31 20:37:12 -07001893 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001894 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001895 final String transportName = mTransport.transportDirName();
1896 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001897
Dan Egnor852f8e42009-09-30 11:20:45 -07001898 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001899 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001901 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001902 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001904
1905 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001906 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001907 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001908 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001909 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001910 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001911 }
Dan Egnor01445162009-09-21 17:04:05 -07001912 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001913
1914 // The package manager doesn't have a proper <application> etc, but since
1915 // it's running here in the system process we can just set up its agent
1916 // directly and use a synthetic BackupRequest. We always run this pass
1917 // because it's cheap and this way we guarantee that we don't get out of
1918 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001919 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001920 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1921 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001922 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001923 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001924 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001925 }
Christopher Tate90967f42009-09-20 15:28:33 -07001926
Christopher Tate8e294d42011-08-31 20:37:12 -07001927 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1928 // The backend reports that our dataset has been wiped. Note this in
1929 // the event log; the no-success code below will reset the backup
1930 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001931 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001932 }
1933 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001934 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001935 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001936 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001937 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001938 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1939 // metadata and its completion/timeout callback will continue the state
1940 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001941 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001942 if (mStatus != BackupConstants.TRANSPORT_OK) {
1943 // if things went wrong at this point, we need to
1944 // restage everything and try again later.
1945 resetBackupState(mStateDir); // Just to make sure.
1946 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001947 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001948 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001949 }
1950
Christopher Tate8e294d42011-08-31 20:37:12 -07001951 // Transport has been initialized and the PM metadata submitted successfully
1952 // if that was warranted. Now we process the single next thing in the queue.
1953 void invokeNextAgent() {
1954 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001955 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001956
Christopher Tate8e294d42011-08-31 20:37:12 -07001957 // Sanity check that we have work to do. If not, skip to the end where
1958 // we reestablish the wakelock invariants etc.
1959 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001960 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001961 executeNextState(BackupState.FINAL);
1962 return;
1963 }
1964
1965 // pop the entry we're going to process on this step
1966 BackupRequest request = mQueue.get(0);
1967 mQueue.remove(0);
1968
1969 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001970 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001971
1972 // Verify that the requested app exists; it might be something that
1973 // requested a backup but was then uninstalled. The request was
1974 // journalled and rather than tamper with the journal it's safer
1975 // to sanity-check here. This also gives us the classname of the
1976 // package's backup agent.
1977 try {
1978 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1979 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001980 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1981 // The manifest has changed but we had a stale backup request pending.
1982 // This won't happen again because the app won't be requesting further
1983 // backups.
1984 Slog.i(TAG, "Package " + request.packageName
1985 + " no longer supports backup; skipping");
1986 addBackupTrace("skipping - no agent, completion is noop");
1987 executeNextState(BackupState.RUNNING_QUEUE);
1988 return;
1989 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001990
Christopher Tate043dadc2009-06-02 16:11:00 -07001991 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001992 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001993 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1994 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001995 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001996 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001997 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001998 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1999 // at this point we'll either get a completion callback from the
2000 // agent, or a timeout message on the main handler. either way, we're
2001 // done here as long as we're successful so far.
2002 } else {
2003 // Timeout waiting for the agent
2004 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002005 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002006 } catch (SecurityException ex) {
2007 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002008 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002009 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002010 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002011 }
2012 } catch (NameNotFoundException e) {
2013 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002014 addBackupTrace("no such package");
2015 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002016 } finally {
2017 mWakelock.setWorkSource(null);
2018
2019 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002020 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002021 if (mStatus != BackupConstants.TRANSPORT_OK) {
2022 BackupState nextState = BackupState.RUNNING_QUEUE;
2023
2024 // An agent-level failure means we reenqueue this one agent for
2025 // a later retry, but otherwise proceed normally.
2026 if (mStatus == BackupConstants.AGENT_ERROR) {
2027 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2028 + " - restaging");
2029 dataChangedImpl(request.packageName);
2030 mStatus = BackupConstants.TRANSPORT_OK;
2031 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002032 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2033 // Failed lookup of the app, so we couldn't bring up an agent, but
2034 // we're otherwise fine. Just drop it and go on to the next as usual.
2035 mStatus = BackupConstants.TRANSPORT_OK;
2036 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002037 // Transport-level failure means we reenqueue everything
2038 revertAndEndBackup();
2039 nextState = BackupState.FINAL;
2040 }
2041
2042 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002043 } else {
2044 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002045 }
2046 }
2047 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002048
Christopher Tate8e294d42011-08-31 20:37:12 -07002049 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002050 addBackupTrace("finishing");
2051
Christopher Tate8e294d42011-08-31 20:37:12 -07002052 // Either backup was successful, in which case we of course do not need
2053 // this pass's journal any more; or it failed, in which case we just
2054 // re-enqueued all of these packages in the current active journal.
2055 // Either way, we no longer need this pass's journal.
2056 if (mJournal != null && !mJournal.delete()) {
2057 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2058 }
2059
2060 // If everything actually went through and this is the first time we've
2061 // done a backup, we can now record what the current backup dataset token
2062 // is.
2063 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002064 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 try {
2066 mCurrentToken = mTransport.getCurrentRestoreSet();
2067 } catch (RemoteException e) {} // can't happen
2068 writeRestoreTokens();
2069 }
2070
Christopher Tate336a6492011-10-05 16:05:43 -07002071 // Set up the next backup pass - at this point we can set mBackupRunning
2072 // to false to allow another pass to fire, because we're done with the
2073 // state machine sequence and the wakelock is refcounted.
2074 synchronized (mQueueLock) {
2075 mBackupRunning = false;
2076 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002077 // Make sure we back up everything and perform the one-time init
2078 clearMetadata();
2079 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002080 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002081 backupNow();
2082 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002083 }
2084
2085 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002086 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002087 Slog.i(TAG, "Backup pass finished.");
2088 mWakelock.release();
2089 }
2090
Christopher Tatee659fb92011-10-10 16:34:50 -07002091 // Remove the PM metadata state. This will generate an init on the next pass.
2092 void clearMetadata() {
2093 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2094 if (pmState.exists()) pmState.delete();
2095 }
2096
Christopher Tate8e294d42011-08-31 20:37:12 -07002097 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2098 // handler in case it doesn't get back to us.
2099 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002100 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002101 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2102 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002103
Christopher Tate8e294d42011-08-31 20:37:12 -07002104 mSavedStateName = new File(mStateDir, packageName);
2105 mBackupDataName = new File(mDataDir, packageName + ".data");
2106 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002107
Christopher Tate8e294d42011-08-31 20:37:12 -07002108 mSavedState = null;
2109 mBackupData = null;
2110 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111
Christopher Tate4a627c72011-04-01 14:43:32 -07002112 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002113 try {
2114 // Look up the package info & signatures. This is first so that if it
2115 // throws an exception, there's no file setup yet that would need to
2116 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002117 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002118 // The metadata 'package' is synthetic; construct one and make
2119 // sure our global state is pointed at it
2120 mCurrentPackage = new PackageInfo();
2121 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002122 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002123
Christopher Tatec7b31e32009-06-10 15:49:30 -07002124 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002125 // the saved-state "file". This is by definition an incremental,
2126 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002127 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002128 ParcelFileDescriptor.MODE_READ_ONLY |
2129 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002130
Christopher Tate8e294d42011-08-31 20:37:12 -07002131 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002132 ParcelFileDescriptor.MODE_READ_WRITE |
2133 ParcelFileDescriptor.MODE_CREATE |
2134 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002135
Christopher Tate8e294d42011-08-31 20:37:12 -07002136 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002137 ParcelFileDescriptor.MODE_READ_WRITE |
2138 ParcelFileDescriptor.MODE_CREATE |
2139 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002140
Christopher Tate44a27902010-01-27 17:15:49 -08002141 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002142 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002143 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002144 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002145 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002146 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002147 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002148 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002149 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2150 e.toString());
2151 agentErrorCleanup();
2152 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002153 }
2154
Christopher Tate8e294d42011-08-31 20:37:12 -07002155 // At this point the agent is off and running. The next thing to happen will
2156 // either be a callback from the agent, at which point we'll process its data
2157 // for transport, or a timeout. Either way the next phase will happen in
2158 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002159 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002160 return BackupConstants.TRANSPORT_OK;
2161 }
2162
2163 @Override
2164 public void operationComplete() {
2165 // Okay, the agent successfully reported back to us. Spin the data off to the
2166 // transport and proceed with the next stage.
2167 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2168 + mCurrentPackage.packageName);
2169 mBackupHandler.removeMessages(MSG_TIMEOUT);
2170 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002171 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002172
2173 ParcelFileDescriptor backupData = null;
2174 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002175 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002176 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002177 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002178 if (mStatus == BackupConstants.TRANSPORT_OK) {
2179 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002180 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002181 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002182 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002183 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002184
Dan Egnor83861e72009-09-17 16:17:55 -07002185 // TODO - We call finishBackup() for each application backed up, because
2186 // we need to know now whether it succeeded or failed. Instead, we should
2187 // hold off on finishBackup() until the end, which implies holding off on
2188 // renaming *all* the output state files (see below) until that happens.
2189
Christopher Tate6de74ff2012-01-17 15:20:32 -08002190 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002191 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002192 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002193 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002194 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002195 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002196 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002197 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002198 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002199 }
2200
2201 // After successful transport, delete the now-stale data
2202 // and juggle the files so that next time we supply the agent
2203 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002204 if (mStatus == BackupConstants.TRANSPORT_OK) {
2205 mBackupDataName.delete();
2206 mNewStateName.renameTo(mSavedStateName);
2207 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2208 mCurrentPackage.packageName, size);
2209 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002210 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002211 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2212 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002213 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002214 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002215 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2216 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2217 mCurrentPackage.packageName);
2218 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002219 } finally {
2220 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002221 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002222
Christopher Tate8e294d42011-08-31 20:37:12 -07002223 // If we encountered an error here it's a transport-level failure. That
2224 // means we need to halt everything and reschedule everything for next time.
2225 final BackupState nextState;
2226 if (mStatus != BackupConstants.TRANSPORT_OK) {
2227 revertAndEndBackup();
2228 nextState = BackupState.FINAL;
2229 } else {
2230 // Success! Proceed with the next app if any, otherwise we're done.
2231 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2232 }
2233
2234 executeNextState(nextState);
2235 }
2236
2237 @Override
2238 public void handleTimeout() {
2239 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2240 // it for the next time we run a backup pass.
2241 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2242 // fail repeatedly (i.e. have proved themselves to be buggy).
2243 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2244 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2245 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002246 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002247 agentErrorCleanup();
2248 dataChangedImpl(mCurrentPackage.packageName);
2249 }
2250
2251 void revertAndEndBackup() {
2252 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002253 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002254 for (BackupRequest request : mOriginalQueue) {
2255 dataChangedImpl(request.packageName);
2256 }
2257 // We also want to reset the backup schedule based on whatever
2258 // the transport suggests by way of retry/backoff time.
2259 restartBackupAlarm();
2260 }
2261
2262 void agentErrorCleanup() {
2263 mBackupDataName.delete();
2264 mNewStateName.delete();
2265 clearAgentState();
2266
2267 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2268 }
2269
2270 // Cleanup common to both success and failure cases
2271 void clearAgentState() {
2272 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2273 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2274 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2275 mSavedState = mBackupData = mNewState = null;
2276 synchronized (mCurrentOpLock) {
2277 mCurrentOperations.clear();
2278 }
2279
2280 // If this was a pseudopackage there's no associated Activity Manager state
2281 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002282 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002283 try { // unbind even on timeout, just in case
2284 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2285 } catch (RemoteException e) {}
2286 }
2287 }
2288
2289 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002290 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002291 synchronized (mQueueLock) {
2292 try {
2293 startBackupAlarmsLocked(mTransport.requestBackupTime());
2294 } catch (RemoteException e) { /* cannot happen */ }
2295 }
2296 }
2297
2298 void executeNextState(BackupState nextState) {
2299 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2300 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002301 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002302 mCurrentState = nextState;
2303 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2304 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002305 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002306 }
2307
Christopher Tatedf01dea2009-06-09 20:45:02 -07002308
Christopher Tate4a627c72011-04-01 14:43:32 -07002309 // ----- Full backup to a file/socket -----
2310
2311 class PerformFullBackupTask implements Runnable {
2312 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002313 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002314 IFullBackupRestoreObserver mObserver;
2315 boolean mIncludeApks;
2316 boolean mIncludeShared;
2317 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002318 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002319 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002320 String mCurrentPassword;
2321 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002322 AtomicBoolean mLatchObject;
2323 File mFilesDir;
2324 File mManifestFile;
2325
Christopher Tate7926a692011-07-11 11:31:57 -07002326 class FullBackupRunner implements Runnable {
2327 PackageInfo mPackage;
2328 IBackupAgent mAgent;
2329 ParcelFileDescriptor mPipe;
2330 int mToken;
2331 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002332 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002333
2334 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002335 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002336 mPackage = pack;
2337 mAgent = agent;
2338 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2339 mToken = token;
2340 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002341 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002342 }
2343
2344 @Override
2345 public void run() {
2346 try {
2347 BackupDataOutput output = new BackupDataOutput(
2348 mPipe.getFileDescriptor());
2349
Christopher Tate73d73692012-01-20 17:11:31 -08002350 if (mWriteManifest) {
2351 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2352 writeAppManifest(mPackage, mManifestFile, mSendApk);
2353 FullBackup.backupToTar(mPackage.packageName, null, null,
2354 mFilesDir.getAbsolutePath(),
2355 mManifestFile.getAbsolutePath(),
2356 output);
2357 }
Christopher Tate7926a692011-07-11 11:31:57 -07002358
2359 if (mSendApk) {
2360 writeApkToBackup(mPackage, output);
2361 }
2362
Christopher Tatec58efa62011-08-01 19:20:14 -07002363 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002364 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002365 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2366 } catch (IOException e) {
2367 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2368 } catch (RemoteException e) {
2369 Slog.e(TAG, "Remote agent vanished during full backup of "
2370 + mPackage.packageName);
2371 } finally {
2372 try {
2373 mPipe.close();
2374 } catch (IOException e) {}
2375 }
2376 }
2377 }
2378
Christopher Tate4a627c72011-04-01 14:43:32 -07002379 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002380 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002381 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002382 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002383 mOutputFile = fd;
2384 mObserver = observer;
2385 mIncludeApks = includeApks;
2386 mIncludeShared = includeShared;
2387 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002388 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002389 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002390 mCurrentPassword = curPassword;
2391 // when backing up, if there is a current backup password, we require that
2392 // the user use a nonempty encryption password as well. if one is supplied
2393 // in the UI we use that, but if the UI was left empty we fall back to the
2394 // current backup password (which was supplied by the user as well).
2395 if (encryptPassword == null || "".equals(encryptPassword)) {
2396 mEncryptPassword = curPassword;
2397 } else {
2398 mEncryptPassword = encryptPassword;
2399 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002400 mLatchObject = latch;
2401
2402 mFilesDir = new File("/data/system");
2403 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2404 }
2405
2406 @Override
2407 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002408 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002409
Christopher Tateb0628bf2011-06-02 15:08:13 -07002410 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002411 sendStartBackup();
2412
2413 // doAllApps supersedes the package set if any
2414 if (mAllApps) {
2415 packagesToBackup = mPackageManager.getInstalledPackages(
2416 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002417 // Exclude system apps if we've been asked to do so
2418 if (mIncludeSystem == false) {
2419 for (int i = 0; i < packagesToBackup.size(); ) {
2420 PackageInfo pkg = packagesToBackup.get(i);
2421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2422 packagesToBackup.remove(i);
2423 } else {
2424 i++;
2425 }
2426 }
2427 }
2428 }
2429
2430 // Now process the command line argument packages, if any. Note that explicitly-
2431 // named system-partition packages will be included even if includeSystem was
2432 // set to false.
2433 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002434 for (String pkgName : mPackages) {
2435 try {
2436 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2437 PackageManager.GET_SIGNATURES));
2438 } catch (NameNotFoundException e) {
2439 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2440 }
2441 }
2442 }
2443
Christopher Tate73d73692012-01-20 17:11:31 -08002444 // Cull any packages that have indicated that backups are not permitted, as well
2445 // as any explicit mention of the 'special' shared-storage agent package (we
2446 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002447 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002448 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002449 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2450 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002451 packagesToBackup.remove(i);
2452 } else {
2453 i++;
2454 }
2455 }
2456
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002457 // Cull any packages that run as system-domain uids but do not define their
2458 // own backup agents
2459 for (int i = 0; i < packagesToBackup.size(); ) {
2460 PackageInfo pkg = packagesToBackup.get(i);
2461 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2462 && (pkg.applicationInfo.backupAgentName == null)) {
2463 if (MORE_DEBUG) {
2464 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2465 }
2466 packagesToBackup.remove(i);
2467 } else {
2468 i++;
2469 }
2470 }
2471
Christopher Tate7926a692011-07-11 11:31:57 -07002472 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002473 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002474
Christopher Tate4a627c72011-04-01 14:43:32 -07002475 PackageInfo pkg = null;
2476 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002477 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002478 boolean compressing = COMPRESS_FULL_BACKUPS;
2479 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002480
Christopher Tateeef4ae42011-08-05 13:15:53 -07002481 // Verify that the given password matches the currently-active
2482 // backup password, if any
2483 if (hasBackupPassword()) {
2484 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2485 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2486 return;
2487 }
2488 }
2489
Christopher Tate7bdb0962011-07-13 19:30:21 -07002490 // Write the global file header. All strings are UTF-8 encoded; lines end
2491 // with a '\n' byte. Actual backup data begins immediately following the
2492 // final '\n'.
2493 //
2494 // line 1: "ANDROID BACKUP"
2495 // line 2: backup file format version, currently "1"
2496 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002497 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2498 //
2499 // When line 4 is not "none", then additional header data follows:
2500 //
2501 // line 5: user password salt [hex]
2502 // line 6: master key checksum salt [hex]
2503 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2504 // line 8: IV of the user key [hex]
2505 // line 9: master key blob [hex]
2506 // IV of the master key, master key itself, master key checksum hash
2507 //
2508 // The master key checksum is the master key plus its checksum salt, run through
2509 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2510 // correct password for decrypting the archive: the master key decrypted from
2511 // the archive using the user-supplied password is also run through PBKDF2 in
2512 // this way, and if the result does not match the checksum as stored in the
2513 // archive, then we know that the user-supplied password does not match the
2514 // archive's.
2515 StringBuilder headerbuf = new StringBuilder(1024);
2516
Christopher Tate7bdb0962011-07-13 19:30:21 -07002517 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002518 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2519 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002520
2521 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002522 // Set up the encryption stage if appropriate, and emit the correct header
2523 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002524 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2525 } else {
2526 headerbuf.append("none\n");
2527 }
2528
Christopher Tate7bdb0962011-07-13 19:30:21 -07002529 byte[] header = headerbuf.toString().getBytes("UTF-8");
2530 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002531
2532 // Set up the compression stage feeding into the encryption stage (if any)
2533 if (compressing) {
2534 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2535 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2536 }
2537
2538 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002539 } catch (Exception e) {
2540 // Should never happen!
2541 Slog.e(TAG, "Unable to emit archive header", e);
2542 return;
2543 }
2544
Christopher Tate73d73692012-01-20 17:11:31 -08002545 // Shared storage if requested
2546 if (mIncludeShared) {
2547 try {
2548 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2549 packagesToBackup.add(pkg);
2550 } catch (NameNotFoundException e) {
2551 Slog.e(TAG, "Unable to find shared-storage backup handler");
2552 }
2553 }
2554
Christopher Tateb0628bf2011-06-02 15:08:13 -07002555 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002556 int N = packagesToBackup.size();
2557 for (int i = 0; i < N; i++) {
2558 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002559 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002560 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002561
Christopher Tate6853fcf2011-08-10 17:52:21 -07002562 // Done!
2563 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002564 } catch (RemoteException e) {
2565 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002566 } catch (Exception e) {
2567 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002568 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002569 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002570 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002571 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002572 mOutputFile.close();
2573 } catch (IOException e) {
2574 /* nothing we can do about this */
2575 }
2576 synchronized (mCurrentOpLock) {
2577 mCurrentOperations.clear();
2578 }
2579 synchronized (mLatchObject) {
2580 mLatchObject.set(true);
2581 mLatchObject.notifyAll();
2582 }
2583 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002584 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002585 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002586 }
2587 }
2588
Christopher Tate2efd2db2011-07-19 16:32:49 -07002589 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2590 OutputStream ofstream) throws Exception {
2591 // User key will be used to encrypt the master key.
2592 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002593 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002594 PBKDF2_HASH_ROUNDS);
2595
2596 // the master key is random for each backup
2597 byte[] masterPw = new byte[256 / 8];
2598 mRng.nextBytes(masterPw);
2599 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2600
2601 // primary encryption of the datastream with the random key
2602 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2603 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2604 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2605 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2606
2607 // line 4: name of encryption algorithm
2608 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2609 headerbuf.append('\n');
2610 // line 5: user password salt [hex]
2611 headerbuf.append(byteArrayToHex(newUserSalt));
2612 headerbuf.append('\n');
2613 // line 6: master key checksum salt [hex]
2614 headerbuf.append(byteArrayToHex(checksumSalt));
2615 headerbuf.append('\n');
2616 // line 7: number of PBKDF2 rounds used [decimal]
2617 headerbuf.append(PBKDF2_HASH_ROUNDS);
2618 headerbuf.append('\n');
2619
2620 // line 8: IV of the user key [hex]
2621 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2622 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2623
2624 byte[] IV = mkC.getIV();
2625 headerbuf.append(byteArrayToHex(IV));
2626 headerbuf.append('\n');
2627
2628 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2629 // [byte] IV length = Niv
2630 // [array of Niv bytes] IV itself
2631 // [byte] master key length = Nmk
2632 // [array of Nmk bytes] master key itself
2633 // [byte] MK checksum hash length = Nck
2634 // [array of Nck bytes] master key checksum hash
2635 //
2636 // The checksum is the (master key + checksum salt), run through the
2637 // stated number of PBKDF2 rounds
2638 IV = c.getIV();
2639 byte[] mk = masterKeySpec.getEncoded();
2640 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2641 checksumSalt, PBKDF2_HASH_ROUNDS);
2642
2643 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2644 + checksum.length + 3);
2645 DataOutputStream mkOut = new DataOutputStream(blob);
2646 mkOut.writeByte(IV.length);
2647 mkOut.write(IV);
2648 mkOut.writeByte(mk.length);
2649 mkOut.write(mk);
2650 mkOut.writeByte(checksum.length);
2651 mkOut.write(checksum);
2652 mkOut.flush();
2653 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2654 headerbuf.append(byteArrayToHex(encryptedMk));
2655 headerbuf.append('\n');
2656
2657 return finalOutput;
2658 }
2659
2660 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002661 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002662 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2663
2664 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2665 IApplicationThread.BACKUP_MODE_FULL);
2666 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002667 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002668 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002669 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002670
Christopher Tateb0628bf2011-06-02 15:08:13 -07002671 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002672 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002673 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002674 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002675 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2676 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2677 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2678
Christopher Tate73d73692012-01-20 17:11:31 -08002679 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002680
Christopher Tate7926a692011-07-11 11:31:57 -07002681 final int token = generateToken();
2682 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002683 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002684 pipes[1].close(); // the runner has dup'd it
2685 pipes[1] = null;
2686 Thread t = new Thread(runner);
2687 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002688
Christopher Tate7926a692011-07-11 11:31:57 -07002689 // Now pull data from the app and stuff it into the compressor
2690 try {
2691 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2692 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002693
Christopher Tate7926a692011-07-11 11:31:57 -07002694 byte[] buffer = new byte[16 * 1024];
2695 int chunkTotal;
2696 while ((chunkTotal = in.readInt()) > 0) {
2697 while (chunkTotal > 0) {
2698 int toRead = (chunkTotal > buffer.length)
2699 ? buffer.length : chunkTotal;
2700 int nRead = in.read(buffer, 0, toRead);
2701 out.write(buffer, 0, nRead);
2702 chunkTotal -= nRead;
2703 }
2704 }
2705 } catch (IOException e) {
2706 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002707 }
2708
Christopher Tateb0628bf2011-06-02 15:08:13 -07002709 if (!waitUntilOperationComplete(token)) {
2710 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2711 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002712 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002713 }
Christopher Tate7926a692011-07-11 11:31:57 -07002714
Christopher Tateb0628bf2011-06-02 15:08:13 -07002715 } catch (IOException e) {
2716 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002717 } finally {
2718 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002719 // flush after every package
2720 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002721 if (pipes != null) {
2722 if (pipes[0] != null) pipes[0].close();
2723 if (pipes[1] != null) pipes[1].close();
2724 }
Christopher Tate7926a692011-07-11 11:31:57 -07002725 } catch (IOException e) {
2726 Slog.w(TAG, "Error bringing down backup stack");
2727 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002728 }
2729 } else {
2730 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2731 }
2732 tearDown(pkg);
2733 }
2734
Christopher Tate79ec80d2011-06-24 14:58:49 -07002735 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2736 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2737 final String appSourceDir = pkg.applicationInfo.sourceDir;
2738 final String apkDir = new File(appSourceDir).getParent();
2739 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2740 apkDir, appSourceDir, output);
2741
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002742 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2743 // doesn't have access to external storage.
2744
Christopher Tate79ec80d2011-06-24 14:58:49 -07002745 // Save associated .obb content if it exists and we did save the apk
2746 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002747 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2748 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002749 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002750 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002751 File[] obbFiles = obbDir.listFiles();
2752 if (obbFiles != null) {
2753 final String obbDirName = obbDir.getAbsolutePath();
2754 for (File obb : obbFiles) {
2755 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2756 obbDirName, obb.getAbsolutePath(), output);
2757 }
2758 }
2759 }
2760 }
2761
Christopher Tate6853fcf2011-08-10 17:52:21 -07002762 private void finalizeBackup(OutputStream out) {
2763 try {
2764 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2765 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2766 out.write(eof);
2767 } catch (IOException e) {
2768 Slog.w(TAG, "Error attempting to finalize backup stream");
2769 }
2770 }
2771
Christopher Tate4a627c72011-04-01 14:43:32 -07002772 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2773 throws IOException {
2774 // Manifest format. All data are strings ending in LF:
2775 // BACKUP_MANIFEST_VERSION, currently 1
2776 //
2777 // Version 1:
2778 // package name
2779 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002780 // platform versionCode
2781 // getInstallerPackageName() for this package (maybe empty)
2782 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002783 // number of signatures == N
2784 // N*: signature byte array in ascii format per Signature.toCharsString()
2785 StringBuilder builder = new StringBuilder(4096);
2786 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2787
2788 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2789 printer.println(pkg.packageName);
2790 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002791 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2792
2793 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2794 printer.println((installerName != null) ? installerName : "");
2795
Christopher Tate4a627c72011-04-01 14:43:32 -07002796 printer.println(withApk ? "1" : "0");
2797 if (pkg.signatures == null) {
2798 printer.println("0");
2799 } else {
2800 printer.println(Integer.toString(pkg.signatures.length));
2801 for (Signature sig : pkg.signatures) {
2802 printer.println(sig.toCharsString());
2803 }
2804 }
2805
2806 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002807 outstream.write(builder.toString().getBytes());
2808 outstream.close();
2809 }
2810
2811 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002812 if (pkg != null) {
2813 final ApplicationInfo app = pkg.applicationInfo;
2814 if (app != null) {
2815 try {
2816 // unbind and tidy up even on timeout or failure, just in case
2817 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002818
Christopher Tateb0628bf2011-06-02 15:08:13 -07002819 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002820 if (app.uid != Process.SYSTEM_UID
2821 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002822 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002823 mActivityManager.killApplicationProcess(app.processName, app.uid);
2824 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002825 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002826 }
2827 } catch (RemoteException e) {
2828 Slog.d(TAG, "Lost app trying to shut down");
2829 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002830 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002831 }
2832 }
2833
2834 // wrappers for observer use
2835 void sendStartBackup() {
2836 if (mObserver != null) {
2837 try {
2838 mObserver.onStartBackup();
2839 } catch (RemoteException e) {
2840 Slog.w(TAG, "full backup observer went away: startBackup");
2841 mObserver = null;
2842 }
2843 }
2844 }
2845
2846 void sendOnBackupPackage(String name) {
2847 if (mObserver != null) {
2848 try {
2849 // TODO: use a more user-friendly name string
2850 mObserver.onBackupPackage(name);
2851 } catch (RemoteException e) {
2852 Slog.w(TAG, "full backup observer went away: backupPackage");
2853 mObserver = null;
2854 }
2855 }
2856 }
2857
2858 void sendEndBackup() {
2859 if (mObserver != null) {
2860 try {
2861 mObserver.onEndBackup();
2862 } catch (RemoteException e) {
2863 Slog.w(TAG, "full backup observer went away: endBackup");
2864 mObserver = null;
2865 }
2866 }
2867 }
2868 }
2869
2870
Christopher Tate75a99702011-05-18 16:28:19 -07002871 // ----- Full restore from a file/socket -----
2872
2873 // Description of a file in the restore datastream
2874 static class FileMetadata {
2875 String packageName; // name of the owning app
2876 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002877 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002878 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2879 String path; // subpath within the semantic domain
2880 long mode; // e.g. 0666 (actually int)
2881 long mtime; // last mod time, UTC time_t (actually int)
2882 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002883
2884 @Override
2885 public String toString() {
2886 StringBuilder sb = new StringBuilder(128);
2887 sb.append("FileMetadata{");
2888 sb.append(packageName); sb.append(',');
2889 sb.append(type); sb.append(',');
2890 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2891 sb.append(size);
2892 sb.append('}');
2893 return sb.toString();
2894 }
Christopher Tate75a99702011-05-18 16:28:19 -07002895 }
2896
2897 enum RestorePolicy {
2898 IGNORE,
2899 ACCEPT,
2900 ACCEPT_IF_APK
2901 }
2902
2903 class PerformFullRestoreTask implements Runnable {
2904 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002905 String mCurrentPassword;
2906 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002907 IFullBackupRestoreObserver mObserver;
2908 AtomicBoolean mLatchObject;
2909 IBackupAgent mAgent;
2910 String mAgentPackage;
2911 ApplicationInfo mTargetApp;
2912 ParcelFileDescriptor[] mPipes = null;
2913
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002914 long mBytes;
2915
Christopher Tate75a99702011-05-18 16:28:19 -07002916 // possible handling states for a given package in the restore dataset
2917 final HashMap<String, RestorePolicy> mPackagePolicies
2918 = new HashMap<String, RestorePolicy>();
2919
2920 // installer package names for each encountered app, derived from the manifests
2921 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2922
2923 // Signatures for a given package found in its manifest file
2924 final HashMap<String, Signature[]> mManifestSignatures
2925 = new HashMap<String, Signature[]>();
2926
2927 // Packages we've already wiped data on when restoring their first file
2928 final HashSet<String> mClearedPackages = new HashSet<String>();
2929
Christopher Tate728a1c42011-07-28 18:03:03 -07002930 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002931 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002932 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002933 mCurrentPassword = curPassword;
2934 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002935 mObserver = observer;
2936 mLatchObject = latch;
2937 mAgent = null;
2938 mAgentPackage = null;
2939 mTargetApp = null;
2940
2941 // Which packages we've already wiped data on. We prepopulate this
2942 // with a whitelist of packages known to be unclearable.
2943 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002944 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002945
Christopher Tate75a99702011-05-18 16:28:19 -07002946 }
2947
2948 class RestoreFileRunnable implements Runnable {
2949 IBackupAgent mAgent;
2950 FileMetadata mInfo;
2951 ParcelFileDescriptor mSocket;
2952 int mToken;
2953
2954 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2955 ParcelFileDescriptor socket, int token) throws IOException {
2956 mAgent = agent;
2957 mInfo = info;
2958 mToken = token;
2959
2960 // This class is used strictly for process-local binder invocations. The
2961 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2962 // do not automatically get a 'dup'ed descriptor that we can can continue
2963 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2964 // before proceeding to do the restore.
2965 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2966 }
2967
2968 @Override
2969 public void run() {
2970 try {
2971 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2972 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2973 mToken, mBackupManagerBinder);
2974 } catch (RemoteException e) {
2975 // never happens; this is used strictly for local binder calls
2976 }
2977 }
2978 }
2979
2980 @Override
2981 public void run() {
2982 Slog.i(TAG, "--- Performing full-dataset restore ---");
2983 sendStartRestore();
2984
Christopher Tateb0628bf2011-06-02 15:08:13 -07002985 // Are we able to restore shared-storage data?
2986 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002987 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002988 }
2989
Christopher Tate2efd2db2011-07-19 16:32:49 -07002990 FileInputStream rawInStream = null;
2991 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002992 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002993 if (hasBackupPassword()) {
2994 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2995 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2996 return;
2997 }
2998 }
2999
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003000 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003001 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003002 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3003 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003004
3005 // First, parse out the unencrypted/uncompressed header
3006 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003007 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003008 final InputStream in;
3009
3010 boolean okay = false;
3011 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3012 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003013 rawDataIn.readFully(streamHeader);
3014 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3015 if (Arrays.equals(magicBytes, streamHeader)) {
3016 // okay, header looks good. now parse out the rest of the fields.
3017 String s = readHeaderLine(rawInStream);
3018 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3019 // okay, it's a version we recognize
3020 s = readHeaderLine(rawInStream);
3021 compressed = (Integer.parseInt(s) != 0);
3022 s = readHeaderLine(rawInStream);
3023 if (s.equals("none")) {
3024 // no more header to parse; we're good to go
3025 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003026 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003027 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3028 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003029 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003030 }
3031 } else Slog.w(TAG, "Archive is encrypted but no password given");
3032 } else Slog.w(TAG, "Wrong header version: " + s);
3033 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003034
3035 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003036 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003037 return;
3038 }
3039
3040 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003041 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003042
3043 boolean didRestore;
3044 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003045 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003046 } while (didRestore);
3047
Christopher Tatec58efa62011-08-01 19:20:14 -07003048 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003049 } catch (IOException e) {
3050 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003051 } finally {
3052 tearDownPipes();
3053 tearDownAgent(mTargetApp);
3054
3055 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003056 if (rawDataIn != null) rawDataIn.close();
3057 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003058 mInputFile.close();
3059 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003060 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003061 /* nothing we can do about this */
3062 }
3063 synchronized (mCurrentOpLock) {
3064 mCurrentOperations.clear();
3065 }
3066 synchronized (mLatchObject) {
3067 mLatchObject.set(true);
3068 mLatchObject.notifyAll();
3069 }
3070 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003071 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003072 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003073 }
3074 }
3075
Christopher Tate7bdb0962011-07-13 19:30:21 -07003076 String readHeaderLine(InputStream in) throws IOException {
3077 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003078 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003079 while ((c = in.read()) >= 0) {
3080 if (c == '\n') break; // consume and discard the newlines
3081 buffer.append((char)c);
3082 }
3083 return buffer.toString();
3084 }
3085
Christopher Tate2efd2db2011-07-19 16:32:49 -07003086 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3087 InputStream result = null;
3088 try {
3089 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3090
3091 String userSaltHex = readHeaderLine(rawInStream); // 5
3092 byte[] userSalt = hexToByteArray(userSaltHex);
3093
3094 String ckSaltHex = readHeaderLine(rawInStream); // 6
3095 byte[] ckSalt = hexToByteArray(ckSaltHex);
3096
3097 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3098 String userIvHex = readHeaderLine(rawInStream); // 8
3099
3100 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3101
3102 // decrypt the master key blob
3103 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003104 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003105 rounds);
3106 byte[] IV = hexToByteArray(userIvHex);
3107 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3108 c.init(Cipher.DECRYPT_MODE,
3109 new SecretKeySpec(userKey.getEncoded(), "AES"),
3110 ivSpec);
3111 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3112 byte[] mkBlob = c.doFinal(mkCipher);
3113
3114 // first, the master key IV
3115 int offset = 0;
3116 int len = mkBlob[offset++];
3117 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3118 offset += len;
3119 // then the master key itself
3120 len = mkBlob[offset++];
3121 byte[] mk = Arrays.copyOfRange(mkBlob,
3122 offset, offset + len);
3123 offset += len;
3124 // and finally the master key checksum hash
3125 len = mkBlob[offset++];
3126 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3127 offset, offset + len);
3128
3129 // now validate the decrypted master key against the checksum
3130 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3131 if (Arrays.equals(calculatedCk, mkChecksum)) {
3132 ivSpec = new IvParameterSpec(IV);
3133 c.init(Cipher.DECRYPT_MODE,
3134 new SecretKeySpec(mk, "AES"),
3135 ivSpec);
3136 // Only if all of the above worked properly will 'result' be assigned
3137 result = new CipherInputStream(rawInStream, c);
3138 } else Slog.w(TAG, "Incorrect password");
3139 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3140 } catch (InvalidAlgorithmParameterException e) {
3141 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3142 } catch (BadPaddingException e) {
3143 // This case frequently occurs when the wrong password is used to decrypt
3144 // the master key. Use the identical "incorrect password" log text as is
3145 // used in the checksum failure log in order to avoid providing additional
3146 // information to an attacker.
3147 Slog.w(TAG, "Incorrect password");
3148 } catch (IllegalBlockSizeException e) {
3149 Slog.w(TAG, "Invalid block size in master key");
3150 } catch (NoSuchAlgorithmException e) {
3151 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3152 } catch (NoSuchPaddingException e) {
3153 Slog.e(TAG, "Needed padding mechanism unavailable!");
3154 } catch (InvalidKeyException e) {
3155 Slog.w(TAG, "Illegal password; aborting");
3156 } catch (NumberFormatException e) {
3157 Slog.w(TAG, "Can't parse restore data header");
3158 } catch (IOException e) {
3159 Slog.w(TAG, "Can't read input header");
3160 }
3161
3162 return result;
3163 }
3164
Christopher Tate75a99702011-05-18 16:28:19 -07003165 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3166 FileMetadata info;
3167 try {
3168 info = readTarHeaders(instream);
3169 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003170 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003171 dumpFileMetadata(info);
3172 }
3173
3174 final String pkg = info.packageName;
3175 if (!pkg.equals(mAgentPackage)) {
3176 // okay, change in package; set up our various
3177 // bookkeeping if we haven't seen it yet
3178 if (!mPackagePolicies.containsKey(pkg)) {
3179 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3180 }
3181
3182 // Clean up the previous agent relationship if necessary,
3183 // and let the observer know we're considering a new app.
3184 if (mAgent != null) {
3185 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3186 tearDownPipes();
3187 tearDownAgent(mTargetApp);
3188 mTargetApp = null;
3189 mAgentPackage = null;
3190 }
3191 }
3192
3193 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3194 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3195 mPackageInstallers.put(pkg, info.installerPackageName);
3196 // We've read only the manifest content itself at this point,
3197 // so consume the footer before looping around to the next
3198 // input file
3199 skipTarPadding(info.size, instream);
3200 sendOnRestorePackage(pkg);
3201 } else {
3202 // Non-manifest, so it's actual file data. Is this a package
3203 // we're ignoring?
3204 boolean okay = true;
3205 RestorePolicy policy = mPackagePolicies.get(pkg);
3206 switch (policy) {
3207 case IGNORE:
3208 okay = false;
3209 break;
3210
3211 case ACCEPT_IF_APK:
3212 // If we're in accept-if-apk state, then the first file we
3213 // see MUST be the apk.
3214 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3215 if (DEBUG) Slog.d(TAG, "APK file; installing");
3216 // Try to install the app.
3217 String installerName = mPackageInstallers.get(pkg);
3218 okay = installApk(info, installerName, instream);
3219 // good to go; promote to ACCEPT
3220 mPackagePolicies.put(pkg, (okay)
3221 ? RestorePolicy.ACCEPT
3222 : RestorePolicy.IGNORE);
3223 // At this point we've consumed this file entry
3224 // ourselves, so just strip the tar footer and
3225 // go on to the next file in the input stream
3226 skipTarPadding(info.size, instream);
3227 return true;
3228 } else {
3229 // File data before (or without) the apk. We can't
3230 // handle it coherently in this case so ignore it.
3231 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3232 okay = false;
3233 }
3234 break;
3235
3236 case ACCEPT:
3237 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3238 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3239 // we can take the data without the apk, so we
3240 // *want* to do so. skip the apk by declaring this
3241 // one file not-okay without changing the restore
3242 // policy for the package.
3243 okay = false;
3244 }
3245 break;
3246
3247 default:
3248 // Something has gone dreadfully wrong when determining
3249 // the restore policy from the manifest. Ignore the
3250 // rest of this package's data.
3251 Slog.e(TAG, "Invalid policy from manifest");
3252 okay = false;
3253 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3254 break;
3255 }
3256
3257 // If the policy is satisfied, go ahead and set up to pipe the
3258 // data to the agent.
3259 if (DEBUG && okay && mAgent != null) {
3260 Slog.i(TAG, "Reusing existing agent instance");
3261 }
3262 if (okay && mAgent == null) {
3263 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3264
3265 try {
3266 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3267
3268 // If we haven't sent any data to this app yet, we probably
3269 // need to clear it first. Check that.
3270 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003271 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003272 // responsible for coherently managing a full
3273 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003274 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003275 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3276 clearApplicationDataSynchronous(pkg);
3277 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003278 if (DEBUG) Slog.d(TAG, "backup agent ("
3279 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003280 }
3281 mClearedPackages.add(pkg);
3282 } else {
3283 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3284 }
3285
3286 // All set; now set up the IPC and launch the agent
3287 setUpPipes();
3288 mAgent = bindToAgentSynchronous(mTargetApp,
3289 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3290 mAgentPackage = pkg;
3291 } catch (IOException e) {
3292 // fall through to error handling
3293 } catch (NameNotFoundException e) {
3294 // fall through to error handling
3295 }
3296
3297 if (mAgent == null) {
3298 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3299 okay = false;
3300 tearDownPipes();
3301 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3302 }
3303 }
3304
3305 // Sanity check: make sure we never give data to the wrong app. This
3306 // should never happen but a little paranoia here won't go amiss.
3307 if (okay && !pkg.equals(mAgentPackage)) {
3308 Slog.e(TAG, "Restoring data for " + pkg
3309 + " but agent is for " + mAgentPackage);
3310 okay = false;
3311 }
3312
3313 // At this point we have an agent ready to handle the full
3314 // restore data as well as a pipe for sending data to
3315 // that agent. Tell the agent to start reading from the
3316 // pipe.
3317 if (okay) {
3318 boolean agentSuccess = true;
3319 long toCopy = info.size;
3320 final int token = generateToken();
3321 try {
3322 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3323 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003324 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003325 // fire up the app's agent listening on the socket. If
3326 // the agent is running in the system process we can't
3327 // just invoke it asynchronously, so we provide a thread
3328 // for it here.
3329 if (mTargetApp.processName.equals("system")) {
3330 Slog.d(TAG, "system process agent - spinning a thread");
3331 RestoreFileRunnable runner = new RestoreFileRunnable(
3332 mAgent, info, mPipes[0], token);
3333 new Thread(runner).start();
3334 } else {
3335 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3336 info.domain, info.path, info.mode, info.mtime,
3337 token, mBackupManagerBinder);
3338 }
3339 } catch (IOException e) {
3340 // couldn't dup the socket for a process-local restore
3341 Slog.d(TAG, "Couldn't establish restore");
3342 agentSuccess = false;
3343 okay = false;
3344 } catch (RemoteException e) {
3345 // whoops, remote agent went away. We'll eat the content
3346 // ourselves, then, and not copy it over.
3347 Slog.e(TAG, "Agent crashed during full restore");
3348 agentSuccess = false;
3349 okay = false;
3350 }
3351
3352 // Copy over the data if the agent is still good
3353 if (okay) {
3354 boolean pipeOkay = true;
3355 FileOutputStream pipe = new FileOutputStream(
3356 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003357 while (toCopy > 0) {
3358 int toRead = (toCopy > buffer.length)
3359 ? buffer.length : (int)toCopy;
3360 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003361 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003362 if (nRead <= 0) break;
3363 toCopy -= nRead;
3364
3365 // send it to the output pipe as long as things
3366 // are still good
3367 if (pipeOkay) {
3368 try {
3369 pipe.write(buffer, 0, nRead);
3370 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003371 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003372 pipeOkay = false;
3373 }
3374 }
3375 }
3376
3377 // done sending that file! Now we just need to consume
3378 // the delta from info.size to the end of block.
3379 skipTarPadding(info.size, instream);
3380
3381 // and now that we've sent it all, wait for the remote
3382 // side to acknowledge receipt
3383 agentSuccess = waitUntilOperationComplete(token);
3384 }
3385
3386 // okay, if the remote end failed at any point, deal with
3387 // it by ignoring the rest of the restore on it
3388 if (!agentSuccess) {
3389 mBackupHandler.removeMessages(MSG_TIMEOUT);
3390 tearDownPipes();
3391 tearDownAgent(mTargetApp);
3392 mAgent = null;
3393 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3394 }
3395 }
3396
3397 // Problems setting up the agent communication, or an already-
3398 // ignored package: skip to the next tar stream entry by
3399 // reading and discarding this file.
3400 if (!okay) {
3401 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3402 long bytesToConsume = (info.size + 511) & ~511;
3403 while (bytesToConsume > 0) {
3404 int toRead = (bytesToConsume > buffer.length)
3405 ? buffer.length : (int)bytesToConsume;
3406 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003407 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003408 if (nRead <= 0) break;
3409 bytesToConsume -= nRead;
3410 }
3411 }
3412 }
3413 }
3414 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003415 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003416 // treat as EOF
3417 info = null;
3418 }
3419
3420 return (info != null);
3421 }
3422
3423 void setUpPipes() throws IOException {
3424 mPipes = ParcelFileDescriptor.createPipe();
3425 }
3426
3427 void tearDownPipes() {
3428 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003429 try {
3430 mPipes[0].close();
3431 mPipes[0] = null;
3432 mPipes[1].close();
3433 mPipes[1] = null;
3434 } catch (IOException e) {
3435 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003436 }
3437 mPipes = null;
3438 }
3439 }
3440
3441 void tearDownAgent(ApplicationInfo app) {
3442 if (mAgent != null) {
3443 try {
3444 // unbind and tidy up even on timeout or failure, just in case
3445 mActivityManager.unbindBackupAgent(app);
3446
3447 // The agent was running with a stub Application object, so shut it down.
3448 // !!! We hardcode the confirmation UI's package name here rather than use a
3449 // manifest flag! TODO something less direct.
3450 if (app.uid != Process.SYSTEM_UID
3451 && !app.packageName.equals("com.android.backupconfirm")) {
3452 if (DEBUG) Slog.d(TAG, "Killing host process");
3453 mActivityManager.killApplicationProcess(app.processName, app.uid);
3454 } else {
3455 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3456 }
3457 } catch (RemoteException e) {
3458 Slog.d(TAG, "Lost app trying to shut down");
3459 }
3460 mAgent = null;
3461 }
3462 }
3463
3464 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3465 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003466 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003467 int mResult;
3468
3469 public void reset() {
3470 synchronized (mDone) {
3471 mDone.set(false);
3472 }
3473 }
3474
3475 public void waitForCompletion() {
3476 synchronized (mDone) {
3477 while (mDone.get() == false) {
3478 try {
3479 mDone.wait();
3480 } catch (InterruptedException e) { }
3481 }
3482 }
3483 }
3484
3485 int getResult() {
3486 return mResult;
3487 }
3488
3489 @Override
3490 public void packageInstalled(String packageName, int returnCode)
3491 throws RemoteException {
3492 synchronized (mDone) {
3493 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003494 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003495 mDone.set(true);
3496 mDone.notifyAll();
3497 }
3498 }
3499 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003500
3501 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3502 final AtomicBoolean mDone = new AtomicBoolean();
3503 int mResult;
3504
3505 public void reset() {
3506 synchronized (mDone) {
3507 mDone.set(false);
3508 }
3509 }
3510
3511 public void waitForCompletion() {
3512 synchronized (mDone) {
3513 while (mDone.get() == false) {
3514 try {
3515 mDone.wait();
3516 } catch (InterruptedException e) { }
3517 }
3518 }
3519 }
3520
3521 @Override
3522 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3523 synchronized (mDone) {
3524 mResult = returnCode;
3525 mDone.set(true);
3526 mDone.notifyAll();
3527 }
3528 }
3529 }
3530
Christopher Tate75a99702011-05-18 16:28:19 -07003531 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003532 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003533
3534 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3535 boolean okay = true;
3536
3537 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3538
3539 // The file content is an .apk file. Copy it out to a staging location and
3540 // attempt to install it.
3541 File apkFile = new File(mDataDir, info.packageName);
3542 try {
3543 FileOutputStream apkStream = new FileOutputStream(apkFile);
3544 byte[] buffer = new byte[32 * 1024];
3545 long size = info.size;
3546 while (size > 0) {
3547 long toRead = (buffer.length < size) ? buffer.length : size;
3548 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003549 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003550 apkStream.write(buffer, 0, didRead);
3551 size -= didRead;
3552 }
3553 apkStream.close();
3554
3555 // make sure the installer can read it
3556 apkFile.setReadable(true, false);
3557
3558 // Now install it
3559 Uri packageUri = Uri.fromFile(apkFile);
3560 mInstallObserver.reset();
3561 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003562 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3563 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003564 mInstallObserver.waitForCompletion();
3565
3566 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3567 // The only time we continue to accept install of data even if the
3568 // apk install failed is if we had already determined that we could
3569 // accept the data regardless.
3570 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3571 okay = false;
3572 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003573 } else {
3574 // Okay, the install succeeded. Make sure it was the right app.
3575 boolean uninstall = false;
3576 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3577 Slog.w(TAG, "Restore stream claimed to include apk for "
3578 + info.packageName + " but apk was really "
3579 + mInstallObserver.mPackageName);
3580 // delete the package we just put in place; it might be fraudulent
3581 okay = false;
3582 uninstall = true;
3583 } else {
3584 try {
3585 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3586 PackageManager.GET_SIGNATURES);
3587 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3588 Slog.w(TAG, "Restore stream contains apk of package "
3589 + info.packageName + " but it disallows backup/restore");
3590 okay = false;
3591 } else {
3592 // So far so good -- do the signatures match the manifest?
3593 Signature[] sigs = mManifestSignatures.get(info.packageName);
3594 if (!signaturesMatch(sigs, pkg)) {
3595 Slog.w(TAG, "Installed app " + info.packageName
3596 + " signatures do not match restore manifest");
3597 okay = false;
3598 uninstall = true;
3599 }
3600 }
3601 } catch (NameNotFoundException e) {
3602 Slog.w(TAG, "Install of package " + info.packageName
3603 + " succeeded but now not found");
3604 okay = false;
3605 }
3606 }
3607
3608 // If we're not okay at this point, we need to delete the package
3609 // that we just installed.
3610 if (uninstall) {
3611 mDeleteObserver.reset();
3612 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3613 mDeleteObserver, 0);
3614 mDeleteObserver.waitForCompletion();
3615 }
Christopher Tate75a99702011-05-18 16:28:19 -07003616 }
3617 } catch (IOException e) {
3618 Slog.e(TAG, "Unable to transcribe restored apk for install");
3619 okay = false;
3620 } finally {
3621 apkFile.delete();
3622 }
3623
3624 return okay;
3625 }
3626
3627 // Given an actual file content size, consume the post-content padding mandated
3628 // by the tar format.
3629 void skipTarPadding(long size, InputStream instream) throws IOException {
3630 long partial = (size + 512) % 512;
3631 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003632 final int needed = 512 - (int)partial;
3633 byte[] buffer = new byte[needed];
3634 if (readExactly(instream, buffer, 0, needed) == needed) {
3635 mBytes += needed;
3636 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003637 }
3638 }
3639
3640 // Returns a policy constant; takes a buffer arg to reduce memory churn
3641 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3642 throws IOException {
3643 // Fail on suspiciously large manifest files
3644 if (info.size > 64 * 1024) {
3645 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3646 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003647
Christopher Tate75a99702011-05-18 16:28:19 -07003648 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003649 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3650 mBytes += info.size;
3651 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003652
3653 RestorePolicy policy = RestorePolicy.IGNORE;
3654 String[] str = new String[1];
3655 int offset = 0;
3656
3657 try {
3658 offset = extractLine(buffer, offset, str);
3659 int version = Integer.parseInt(str[0]);
3660 if (version == BACKUP_MANIFEST_VERSION) {
3661 offset = extractLine(buffer, offset, str);
3662 String manifestPackage = str[0];
3663 // TODO: handle <original-package>
3664 if (manifestPackage.equals(info.packageName)) {
3665 offset = extractLine(buffer, offset, str);
3666 version = Integer.parseInt(str[0]); // app version
3667 offset = extractLine(buffer, offset, str);
3668 int platformVersion = Integer.parseInt(str[0]);
3669 offset = extractLine(buffer, offset, str);
3670 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3671 offset = extractLine(buffer, offset, str);
3672 boolean hasApk = str[0].equals("1");
3673 offset = extractLine(buffer, offset, str);
3674 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003675 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003676 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003677 for (int i = 0; i < numSigs; i++) {
3678 offset = extractLine(buffer, offset, str);
3679 sigs[i] = new Signature(str[0]);
3680 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003681 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003682
3683 // Okay, got the manifest info we need...
3684 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003685 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3686 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003687 // Fall through to IGNORE if the app explicitly disallows backup
3688 final int flags = pkgInfo.applicationInfo.flags;
3689 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003690 // Restore system-uid-space packages only if they have
3691 // defined a custom backup agent
3692 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3693 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3694 // Verify signatures against any installed version; if they
3695 // don't match, then we fall though and ignore the data. The
3696 // signatureMatch() method explicitly ignores the signature
3697 // check for packages installed on the system partition, because
3698 // such packages are signed with the platform cert instead of
3699 // the app developer's cert, so they're different on every
3700 // device.
3701 if (signaturesMatch(sigs, pkgInfo)) {
3702 if (pkgInfo.versionCode >= version) {
3703 Slog.i(TAG, "Sig + version match; taking data");
3704 policy = RestorePolicy.ACCEPT;
3705 } else {
3706 // The data is from a newer version of the app than
3707 // is presently installed. That means we can only
3708 // use it if the matching apk is also supplied.
3709 Slog.d(TAG, "Data version " + version
3710 + " is newer than installed version "
3711 + pkgInfo.versionCode + " - requiring apk");
3712 policy = RestorePolicy.ACCEPT_IF_APK;
3713 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003714 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003715 Slog.w(TAG, "Restore manifest signatures do not match "
3716 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003717 }
Christopher Tate75a99702011-05-18 16:28:19 -07003718 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003719 Slog.w(TAG, "Package " + info.packageName
3720 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003721 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003722 } else {
3723 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3724 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003725 }
3726 } catch (NameNotFoundException e) {
3727 // Okay, the target app isn't installed. We can process
3728 // the restore properly only if the dataset provides the
3729 // apk file and we can successfully install it.
3730 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3731 + " not installed; requiring apk in dataset");
3732 policy = RestorePolicy.ACCEPT_IF_APK;
3733 }
3734
3735 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3736 Slog.i(TAG, "Cannot restore package " + info.packageName
3737 + " without the matching .apk");
3738 }
3739 } else {
3740 Slog.i(TAG, "Missing signature on backed-up package "
3741 + info.packageName);
3742 }
3743 } else {
3744 Slog.i(TAG, "Expected package " + info.packageName
3745 + " but restore manifest claims " + manifestPackage);
3746 }
3747 } else {
3748 Slog.i(TAG, "Unknown restore manifest version " + version
3749 + " for package " + info.packageName);
3750 }
3751 } catch (NumberFormatException e) {
3752 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003753 } catch (IllegalArgumentException e) {
3754 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003755 }
3756
3757 return policy;
3758 }
3759
3760 // Builds a line from a byte buffer starting at 'offset', and returns
3761 // the index of the next unconsumed data in the buffer.
3762 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3763 final int end = buffer.length;
3764 if (offset >= end) throw new IOException("Incomplete data");
3765
3766 int pos;
3767 for (pos = offset; pos < end; pos++) {
3768 byte c = buffer[pos];
3769 // at LF we declare end of line, and return the next char as the
3770 // starting point for the next time through
3771 if (c == '\n') {
3772 break;
3773 }
3774 }
3775 outStr[0] = new String(buffer, offset, pos - offset);
3776 pos++; // may be pointing an extra byte past the end but that's okay
3777 return pos;
3778 }
3779
3780 void dumpFileMetadata(FileMetadata info) {
3781 if (DEBUG) {
3782 StringBuilder b = new StringBuilder(128);
3783
3784 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003785 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003786 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3787 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3788 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3789 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3790 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3791 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3792 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3793 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3794 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3795 b.append(String.format(" %9d ", info.size));
3796
3797 Date stamp = new Date(info.mtime);
3798 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3799
3800 b.append(info.packageName);
3801 b.append(" :: ");
3802 b.append(info.domain);
3803 b.append(" :: ");
3804 b.append(info.path);
3805
3806 Slog.i(TAG, b.toString());
3807 }
3808 }
3809 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3810 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3811 byte[] block = new byte[512];
3812 FileMetadata info = null;
3813
3814 boolean gotHeader = readTarHeader(instream, block);
3815 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003816 try {
3817 // okay, presume we're okay, and extract the various metadata
3818 info = new FileMetadata();
3819 info.size = extractRadix(block, 124, 12, 8);
3820 info.mtime = extractRadix(block, 136, 12, 8);
3821 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003822
Christopher Tate2efd2db2011-07-19 16:32:49 -07003823 info.path = extractString(block, 345, 155); // prefix
3824 String path = extractString(block, 0, 100);
3825 if (path.length() > 0) {
3826 if (info.path.length() > 0) info.path += '/';
3827 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003828 }
Christopher Tate75a99702011-05-18 16:28:19 -07003829
Christopher Tate2efd2db2011-07-19 16:32:49 -07003830 // tar link indicator field: 1 byte at offset 156 in the header.
3831 int typeChar = block[156];
3832 if (typeChar == 'x') {
3833 // pax extended header, so we need to read that
3834 gotHeader = readPaxExtendedHeader(instream, info);
3835 if (gotHeader) {
3836 // and after a pax extended header comes another real header -- read
3837 // that to find the real file type
3838 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003839 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003840 if (!gotHeader) throw new IOException("Bad or missing pax header");
3841
3842 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003843 }
Christopher Tate75a99702011-05-18 16:28:19 -07003844
Christopher Tate2efd2db2011-07-19 16:32:49 -07003845 switch (typeChar) {
3846 case '0': info.type = BackupAgent.TYPE_FILE; break;
3847 case '5': {
3848 info.type = BackupAgent.TYPE_DIRECTORY;
3849 if (info.size != 0) {
3850 Slog.w(TAG, "Directory entry with nonzero size in header");
3851 info.size = 0;
3852 }
3853 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003854 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003855 case 0: {
3856 // presume EOF
3857 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3858 return null;
3859 }
3860 default: {
3861 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3862 throw new IOException("Unknown entity type " + typeChar);
3863 }
Christopher Tate75a99702011-05-18 16:28:19 -07003864 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003865
3866 // Parse out the path
3867 //
3868 // first: apps/shared/unrecognized
3869 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3870 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3871 // File in shared storage. !!! TODO: implement this.
3872 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003873 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003874 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3875 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3876 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3877 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3878 // App content! Parse out the package name and domain
3879
3880 // strip the apps/ prefix
3881 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3882
3883 // extract the package name
3884 int slash = info.path.indexOf('/');
3885 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3886 info.packageName = info.path.substring(0, slash);
3887 info.path = info.path.substring(slash+1);
3888
3889 // if it's a manifest we're done, otherwise parse out the domains
3890 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3891 slash = info.path.indexOf('/');
3892 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3893 info.domain = info.path.substring(0, slash);
3894 // validate that it's one of the domains we understand
3895 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3896 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3897 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3898 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3899 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
Christopher Tate5cb5c332013-02-21 14:32:12 -08003900 && !info.domain.equals(FullBackup.MANAGED_EXTERNAL_TREE_TOKEN)
Christopher Tate2efd2db2011-07-19 16:32:49 -07003901 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3902 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3903 throw new IOException("Unrecognized domain " + info.domain);
3904 }
3905
3906 info.path = info.path.substring(slash + 1);
3907 }
3908 }
3909 } catch (IOException e) {
3910 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003911 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003912 HEXLOG(block);
3913 }
3914 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003915 }
3916 }
3917 return info;
3918 }
3919
Christopher Tate2efd2db2011-07-19 16:32:49 -07003920 private void HEXLOG(byte[] block) {
3921 int offset = 0;
3922 int todo = block.length;
3923 StringBuilder buf = new StringBuilder(64);
3924 while (todo > 0) {
3925 buf.append(String.format("%04x ", offset));
3926 int numThisLine = (todo > 16) ? 16 : todo;
3927 for (int i = 0; i < numThisLine; i++) {
3928 buf.append(String.format("%02x ", block[offset+i]));
3929 }
3930 Slog.i("hexdump", buf.toString());
3931 buf.setLength(0);
3932 todo -= numThisLine;
3933 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003934 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003935 }
3936
Christopher Tate6853fcf2011-08-10 17:52:21 -07003937 // Read exactly the given number of bytes into a buffer at the stated offset.
3938 // Returns false if EOF is encountered before the requested number of bytes
3939 // could be read.
3940 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3941 throws IOException {
3942 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3943
3944 int soFar = 0;
3945 while (soFar < size) {
3946 int nRead = in.read(buffer, offset + soFar, size - soFar);
3947 if (nRead <= 0) {
3948 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3949 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003950 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003951 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003952 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003953 return soFar;
3954 }
3955
3956 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3957 final int got = readExactly(instream, block, 0, 512);
3958 if (got == 0) return false; // Clean EOF
3959 if (got < 512) throw new IOException("Unable to read full block header");
3960 mBytes += 512;
3961 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003962 }
3963
3964 // overwrites 'info' fields based on the pax extended header
3965 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3966 throws IOException {
3967 // We should never see a pax extended header larger than this
3968 if (info.size > 32*1024) {
3969 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3970 + " - aborting");
3971 throw new IOException("Sanity failure: pax header size " + info.size);
3972 }
3973
3974 // read whole blocks, not just the content size
3975 int numBlocks = (int)((info.size + 511) >> 9);
3976 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003977 if (readExactly(instream, data, 0, data.length) < data.length) {
3978 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003979 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003980 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003981
3982 final int contentSize = (int) info.size;
3983 int offset = 0;
3984 do {
3985 // extract the line at 'offset'
3986 int eol = offset+1;
3987 while (eol < contentSize && data[eol] != ' ') eol++;
3988 if (eol >= contentSize) {
3989 // error: we just hit EOD looking for the end of the size field
3990 throw new IOException("Invalid pax data");
3991 }
3992 // eol points to the space between the count and the key
3993 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3994 int key = eol + 1; // start of key=value
3995 eol = offset + linelen - 1; // trailing LF
3996 int value;
3997 for (value = key+1; data[value] != '=' && value <= eol; value++);
3998 if (value > eol) {
3999 throw new IOException("Invalid pax declaration");
4000 }
4001
4002 // pax requires that key/value strings be in UTF-8
4003 String keyStr = new String(data, key, value-key, "UTF-8");
4004 // -1 to strip the trailing LF
4005 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4006
4007 if ("path".equals(keyStr)) {
4008 info.path = valStr;
4009 } else if ("size".equals(keyStr)) {
4010 info.size = Long.parseLong(valStr);
4011 } else {
4012 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4013 }
4014
4015 offset += linelen;
4016 } while (offset < contentSize);
4017
4018 return true;
4019 }
4020
4021 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4022 throws IOException {
4023 long value = 0;
4024 final int end = offset + maxChars;
4025 for (int i = offset; i < end; i++) {
4026 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004027 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004028 if (b == 0 || b == ' ') break;
4029 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004030 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004031 }
4032 value = radix * value + (b - '0');
4033 }
4034 return value;
4035 }
4036
4037 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4038 final int end = offset + maxChars;
4039 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004040 // tar string fields terminate early with a NUL
4041 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004042 return new String(data, offset, eos-offset, "US-ASCII");
4043 }
4044
4045 void sendStartRestore() {
4046 if (mObserver != null) {
4047 try {
4048 mObserver.onStartRestore();
4049 } catch (RemoteException e) {
4050 Slog.w(TAG, "full restore observer went away: startRestore");
4051 mObserver = null;
4052 }
4053 }
4054 }
4055
4056 void sendOnRestorePackage(String name) {
4057 if (mObserver != null) {
4058 try {
4059 // TODO: use a more user-friendly name string
4060 mObserver.onRestorePackage(name);
4061 } catch (RemoteException e) {
4062 Slog.w(TAG, "full restore observer went away: restorePackage");
4063 mObserver = null;
4064 }
4065 }
4066 }
4067
4068 void sendEndRestore() {
4069 if (mObserver != null) {
4070 try {
4071 mObserver.onEndRestore();
4072 } catch (RemoteException e) {
4073 Slog.w(TAG, "full restore observer went away: endRestore");
4074 mObserver = null;
4075 }
4076 }
4077 }
4078 }
4079
Christopher Tatedf01dea2009-06-09 20:45:02 -07004080 // ----- Restore handling -----
4081
Christopher Tate78dd4a72009-11-04 11:49:08 -08004082 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4083 // If the target resides on the system partition, we allow it to restore
4084 // data from the like-named package in a restore set even if the signatures
4085 // do not match. (Unlike general applications, those flashed to the system
4086 // partition will be signed with the device's platform certificate, so on
4087 // different phones the same system app will have different signatures.)
4088 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004089 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004090 return true;
4091 }
4092
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004093 // Allow unsigned apps, but not signed on one device and unsigned on the other
4094 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004095 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004096 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004097 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004098 if ((storedSigs == null || storedSigs.length == 0)
4099 && (deviceSigs == null || deviceSigs.length == 0)) {
4100 return true;
4101 }
4102 if (storedSigs == null || deviceSigs == null) {
4103 return false;
4104 }
4105
Christopher Tateabce4e82009-06-18 18:35:32 -07004106 // !!! TODO: this demands that every stored signature match one
4107 // that is present on device, and does not demand the converse.
4108 // Is this this right policy?
4109 int nStored = storedSigs.length;
4110 int nDevice = deviceSigs.length;
4111
4112 for (int i=0; i < nStored; i++) {
4113 boolean match = false;
4114 for (int j=0; j < nDevice; j++) {
4115 if (storedSigs[i].equals(deviceSigs[j])) {
4116 match = true;
4117 break;
4118 }
4119 }
4120 if (!match) {
4121 return false;
4122 }
4123 }
4124 return true;
4125 }
4126
Christopher Tate2982d062011-09-06 20:35:24 -07004127 enum RestoreState {
4128 INITIAL,
4129 DOWNLOAD_DATA,
4130 PM_METADATA,
4131 RUNNING_QUEUE,
4132 FINAL
4133 }
4134
4135 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004136 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004137 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004138 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004139 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004140 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004141 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004142 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004143 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004144 private long mStartRealtime;
4145 private PackageManagerBackupAgent mPmAgent;
4146 private List<PackageInfo> mAgentPackages;
4147 private ArrayList<PackageInfo> mRestorePackages;
4148 private RestoreState mCurrentState;
4149 private int mCount;
4150 private boolean mFinished;
4151 private int mStatus;
4152 private File mBackupDataName;
4153 private File mNewStateName;
4154 private File mSavedStateName;
4155 private ParcelFileDescriptor mBackupData;
4156 private ParcelFileDescriptor mNewState;
4157 private PackageInfo mCurrentPackage;
4158
Christopher Tatedf01dea2009-06-09 20:45:02 -07004159
Christopher Tate5cbbf562009-06-22 16:44:51 -07004160 class RestoreRequest {
4161 public PackageInfo app;
4162 public int storedAppVersion;
4163
4164 RestoreRequest(PackageInfo _app, int _version) {
4165 app = _app;
4166 storedAppVersion = _version;
4167 }
4168 }
4169
Christopher Tate44a27902010-01-27 17:15:49 -08004170 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004171 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004172 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004173 mCurrentState = RestoreState.INITIAL;
4174 mFinished = false;
4175 mPmAgent = null;
4176
Christopher Tatedf01dea2009-06-09 20:45:02 -07004177 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004178 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004179 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004180 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004181 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004182 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004183
Christopher Tate284f1bb2011-07-07 14:31:18 -07004184 if (filterSet != null) {
4185 mFilterSet = new HashSet<String>();
4186 for (String pkg : filterSet) {
4187 mFilterSet.add(pkg);
4188 }
4189 } else {
4190 mFilterSet = null;
4191 }
4192
Christopher Tate5cb400b2009-06-25 16:03:14 -07004193 try {
4194 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4195 } catch (RemoteException e) {
4196 // can't happen; the transport is local
4197 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004198 }
4199
Christopher Tate2982d062011-09-06 20:35:24 -07004200 // Execute one tick of whatever state machine the task implements
4201 @Override
4202 public void execute() {
4203 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4204 switch (mCurrentState) {
4205 case INITIAL:
4206 beginRestore();
4207 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004208
Christopher Tate2982d062011-09-06 20:35:24 -07004209 case DOWNLOAD_DATA:
4210 downloadRestoreData();
4211 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004212
Christopher Tate2982d062011-09-06 20:35:24 -07004213 case PM_METADATA:
4214 restorePmMetadata();
4215 break;
4216
4217 case RUNNING_QUEUE:
4218 restoreNextAgent();
4219 break;
4220
4221 case FINAL:
4222 if (!mFinished) finalizeRestore();
4223 else {
4224 Slog.e(TAG, "Duplicate finish");
4225 }
4226 mFinished = true;
4227 break;
4228 }
4229 }
4230
4231 // Initialize and set up for the PM metadata restore, which comes first
4232 void beginRestore() {
4233 // Don't account time doing the restore as inactivity of the app
4234 // that has opened a restore session.
4235 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4236
4237 // Assume error until we successfully init everything
4238 mStatus = BackupConstants.TRANSPORT_ERROR;
4239
Christopher Tatedf01dea2009-06-09 20:45:02 -07004240 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004241 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004242 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004243
Dan Egnorefe52642009-06-24 00:16:33 -07004244 // Get the list of all packages which have backup enabled.
4245 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004246 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004247 PackageInfo omPackage = new PackageInfo();
4248 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004249 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004250
Christopher Tate2982d062011-09-06 20:35:24 -07004251 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004252 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004253 // if there's a filter set, strip out anything that isn't
4254 // present before proceeding
4255 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004256 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4257 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004258 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004259 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004260 }
4261 }
Christopher Tate2982d062011-09-06 20:35:24 -07004262 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004263 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004264 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004265 Slog.i(TAG, " " + p);
4266 }
4267 }
4268 }
Christopher Tate2982d062011-09-06 20:35:24 -07004269 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004270 } else {
4271 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004272 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004273 }
Dan Egnorefe52642009-06-24 00:16:33 -07004274
Christopher Tate7d562ec2009-06-25 18:03:43 -07004275 // let the observer know that we're running
4276 if (mObserver != null) {
4277 try {
4278 // !!! TODO: get an actual count from the transport after
4279 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004280 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004281 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004282 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004283 mObserver = null;
4284 }
4285 }
Christopher Tate2982d062011-09-06 20:35:24 -07004286 } catch (RemoteException e) {
4287 // Something has gone catastrophically wrong with the transport
4288 Slog.e(TAG, "Error communicating with transport for restore");
4289 executeNextState(RestoreState.FINAL);
4290 return;
4291 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004292
Christopher Tate2982d062011-09-06 20:35:24 -07004293 mStatus = BackupConstants.TRANSPORT_OK;
4294 executeNextState(RestoreState.DOWNLOAD_DATA);
4295 }
4296
4297 void downloadRestoreData() {
4298 // Note that the download phase can be very time consuming, but we're executing
4299 // it inline here on the looper. This is "okay" because it is not calling out to
4300 // third party code; the transport is "trusted," and so we assume it is being a
4301 // good citizen and timing out etc when appropriate.
4302 //
4303 // TODO: when appropriate, move the download off the looper and rearrange the
4304 // error handling around that.
4305 try {
4306 mStatus = mTransport.startRestore(mToken,
4307 mRestorePackages.toArray(new PackageInfo[0]));
4308 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004310 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004311 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004312 return;
4313 }
Christopher Tate2982d062011-09-06 20:35:24 -07004314 } catch (RemoteException e) {
4315 Slog.e(TAG, "Error communicating with transport for restore");
4316 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4317 mStatus = BackupConstants.TRANSPORT_ERROR;
4318 executeNextState(RestoreState.FINAL);
4319 return;
4320 }
Dan Egnorefe52642009-06-24 00:16:33 -07004321
Christopher Tate2982d062011-09-06 20:35:24 -07004322 // Successful download of the data to be parceled out to the apps, so off we go.
4323 executeNextState(RestoreState.PM_METADATA);
4324 }
4325
4326 void restorePmMetadata() {
4327 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004328 String packageName = mTransport.nextRestorePackage();
4329 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004330 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004331 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004332 mStatus = BackupConstants.TRANSPORT_ERROR;
4333 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004334 return;
4335 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004336 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004337 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004338 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004339 mStatus = BackupConstants.TRANSPORT_OK;
4340 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004341 return;
4342 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004343 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004344 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004345 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004346 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004347 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004348 return;
4349 }
4350
4351 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004352 PackageInfo omPackage = new PackageInfo();
4353 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4354 mPmAgent = new PackageManagerBackupAgent(
4355 mPackageManager, mAgentPackages);
4356 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004357 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004358 // The PM agent called operationComplete() already, because our invocation
4359 // of it is process-local and therefore synchronous. That means that a
4360 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4361 // proceed with running the queue do we remove that pending message and
4362 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004363
Christopher Tate8c032472009-07-02 14:28:47 -07004364 // Verify that the backup set includes metadata. If not, we can't do
4365 // signature/version verification etc, so we simply do not proceed with
4366 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004367 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004368 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004369 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004370 "Package manager restore metadata missing");
4371 mStatus = BackupConstants.TRANSPORT_ERROR;
4372 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4373 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004374 return;
4375 }
Christopher Tate2982d062011-09-06 20:35:24 -07004376 } catch (RemoteException e) {
4377 Slog.e(TAG, "Error communicating with transport for restore");
4378 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4379 mStatus = BackupConstants.TRANSPORT_ERROR;
4380 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4381 executeNextState(RestoreState.FINAL);
4382 return;
4383 }
Christopher Tate8c032472009-07-02 14:28:47 -07004384
Christopher Tate2982d062011-09-06 20:35:24 -07004385 // Metadata is intact, so we can now run the restore queue. If we get here,
4386 // we have already enqueued the necessary next-step message on the looper.
4387 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004388
Christopher Tate2982d062011-09-06 20:35:24 -07004389 void restoreNextAgent() {
4390 try {
4391 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004392
Christopher Tate2982d062011-09-06 20:35:24 -07004393 if (packageName == null) {
4394 Slog.e(TAG, "Error getting next restore package");
4395 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4396 executeNextState(RestoreState.FINAL);
4397 return;
4398 } else if (packageName.equals("")) {
4399 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4400 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4401 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4402 executeNextState(RestoreState.FINAL);
4403 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004404 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004405
4406 if (mObserver != null) {
4407 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004408 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004409 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004410 Slog.d(TAG, "Restore observer died in onUpdate");
4411 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004412 }
4413 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004414
Christopher Tate2982d062011-09-06 20:35:24 -07004415 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4416 if (metaInfo == null) {
4417 Slog.e(TAG, "Missing metadata for " + packageName);
4418 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4419 "Package metadata missing");
4420 executeNextState(RestoreState.RUNNING_QUEUE);
4421 return;
Christopher Tate84725812010-02-04 15:52:40 -08004422 }
4423
Christopher Tate2982d062011-09-06 20:35:24 -07004424 PackageInfo packageInfo;
4425 try {
4426 int flags = PackageManager.GET_SIGNATURES;
4427 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4428 } catch (NameNotFoundException e) {
4429 Slog.e(TAG, "Invalid package restoring data", e);
4430 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4431 "Package missing on device");
4432 executeNextState(RestoreState.RUNNING_QUEUE);
4433 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004434 }
4435
Christopher Tatee7287a02012-09-07 18:32:12 -07004436 if (packageInfo.applicationInfo.backupAgentName == null
4437 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4438 if (DEBUG) {
4439 Slog.i(TAG, "Data exists for package " + packageName
4440 + " but app has no agent; skipping");
4441 }
4442 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4443 "Package has no agent");
4444 executeNextState(RestoreState.RUNNING_QUEUE);
4445 return;
4446 }
4447
Christopher Tate2982d062011-09-06 20:35:24 -07004448 if (metaInfo.versionCode > packageInfo.versionCode) {
4449 // Data is from a "newer" version of the app than we have currently
4450 // installed. If the app has not declared that it is prepared to
4451 // handle this case, we do not attempt the restore.
4452 if ((packageInfo.applicationInfo.flags
4453 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4454 String message = "Version " + metaInfo.versionCode
4455 + " > installed version " + packageInfo.versionCode;
4456 Slog.w(TAG, "Package " + packageName + ": " + message);
4457 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4458 packageName, message);
4459 executeNextState(RestoreState.RUNNING_QUEUE);
4460 return;
4461 } else {
4462 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4463 + " > installed " + packageInfo.versionCode
4464 + " but restoreAnyVersion");
4465 }
4466 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004467
Christopher Tate2982d062011-09-06 20:35:24 -07004468 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4469 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4470 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4471 "Signature mismatch");
4472 executeNextState(RestoreState.RUNNING_QUEUE);
4473 return;
4474 }
4475
4476 if (DEBUG) Slog.v(TAG, "Package " + packageName
4477 + " restore version [" + metaInfo.versionCode
4478 + "] is compatible with installed version ["
4479 + packageInfo.versionCode + "]");
4480
4481 // Then set up and bind the agent
4482 IBackupAgent agent = bindToAgentSynchronous(
4483 packageInfo.applicationInfo,
4484 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4485 if (agent == null) {
4486 Slog.w(TAG, "Can't find backup agent for " + packageName);
4487 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4488 "Restore agent missing");
4489 executeNextState(RestoreState.RUNNING_QUEUE);
4490 return;
4491 }
4492
4493 // And then finally start the restore on this agent
4494 try {
4495 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4496 ++mCount;
4497 } catch (Exception e) {
4498 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4499 agentErrorCleanup();
4500 executeNextState(RestoreState.RUNNING_QUEUE);
4501 }
4502 } catch (RemoteException e) {
4503 Slog.e(TAG, "Unable to fetch restore data from transport");
4504 mStatus = BackupConstants.TRANSPORT_ERROR;
4505 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004506 }
4507 }
4508
Christopher Tate2982d062011-09-06 20:35:24 -07004509 void finalizeRestore() {
4510 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4511
4512 try {
4513 mTransport.finishRestore();
4514 } catch (RemoteException e) {
4515 Slog.e(TAG, "Error finishing restore", e);
4516 }
4517
4518 if (mObserver != null) {
4519 try {
4520 mObserver.restoreFinished(mStatus);
4521 } catch (RemoteException e) {
4522 Slog.d(TAG, "Restore observer died at restoreFinished");
4523 }
4524 }
4525
4526 // If this was a restoreAll operation, record that this was our
4527 // ancestral dataset, as well as the set of apps that are possibly
4528 // restoreable from the dataset
4529 if (mTargetPackage == null && mPmAgent != null) {
4530 mAncestralPackages = mPmAgent.getRestoredPackages();
4531 mAncestralToken = mToken;
4532 writeRestoreTokens();
4533 }
4534
4535 // We must under all circumstances tell the Package Manager to
4536 // proceed with install notifications if it's waiting for us.
4537 if (mPmToken > 0) {
4538 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4539 try {
4540 mPackageManagerBinder.finishPackageInstall(mPmToken);
4541 } catch (RemoteException e) { /* can't happen */ }
4542 }
4543
4544 // Furthermore we need to reset the session timeout clock
4545 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4546 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4547 TIMEOUT_RESTORE_INTERVAL);
4548
4549 // done; we can finally release the wakelock
4550 Slog.i(TAG, "Restore complete.");
4551 mWakelock.release();
4552 }
4553
4554 // Call asynchronously into the app, passing it the restore data. The next step
4555 // after this is always a callback, either operationComplete() or handleTimeout().
4556 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004557 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004558 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004559 final String packageName = app.packageName;
4560
Christopher Tate2982d062011-09-06 20:35:24 -07004561 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004562
Christopher Tatec7b31e32009-06-10 15:49:30 -07004563 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004564 mBackupDataName = new File(mDataDir, packageName + ".restore");
4565 mNewStateName = new File(mStateDir, packageName + ".new");
4566 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004567
Christopher Tate4a627c72011-04-01 14:43:32 -07004568 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004569 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004570 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004571 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004572 ParcelFileDescriptor.MODE_READ_WRITE |
4573 ParcelFileDescriptor.MODE_CREATE |
4574 ParcelFileDescriptor.MODE_TRUNCATE);
4575
Christopher Tate2982d062011-09-06 20:35:24 -07004576 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004577 // Transport-level failure, so we wind everything up and
4578 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004579 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004580 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004581 mBackupData.close();
4582 mBackupDataName.delete();
4583 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004584 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004585 }
4586
4587 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004588 mBackupData.close();
4589 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004590 ParcelFileDescriptor.MODE_READ_ONLY);
4591
Christopher Tate2982d062011-09-06 20:35:24 -07004592 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004593 ParcelFileDescriptor.MODE_READ_WRITE |
4594 ParcelFileDescriptor.MODE_CREATE |
4595 ParcelFileDescriptor.MODE_TRUNCATE);
4596
Christopher Tate44a27902010-01-27 17:15:49 -08004597 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004598 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4599 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004600 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004601 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004602 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004603 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004604
Christopher Tate2982d062011-09-06 20:35:24 -07004605 // After a restore failure we go back to running the queue. If there
4606 // are no more packages to be restored that will be handled by the
4607 // next step.
4608 executeNextState(RestoreState.RUNNING_QUEUE);
4609 }
4610 }
Chris Tate249345b2010-10-29 12:57:04 -07004611
Christopher Tate2982d062011-09-06 20:35:24 -07004612 void agentErrorCleanup() {
4613 // If the agent fails restore, it might have put the app's data
4614 // into an incoherent state. For consistency we wipe its data
4615 // again in this case before continuing with normal teardown
4616 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4617 agentCleanup();
4618 }
4619
4620 void agentCleanup() {
4621 mBackupDataName.delete();
4622 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4623 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4624 mBackupData = mNewState = null;
4625
4626 // if everything went okay, remember the recorded state now
4627 //
4628 // !!! TODO: the restored data should be migrated on the server
4629 // side into the current dataset. In that case the new state file
4630 // we just created would reflect the data already extant in the
4631 // backend, so there'd be nothing more to do. Until that happens,
4632 // however, we need to make sure that we record the data to the
4633 // current backend dataset. (Yes, this means shipping the data over
4634 // the wire in both directions. That's bad, but consistency comes
4635 // first, then efficiency.) Once we introduce server-side data
4636 // migration to the newly-restored device's dataset, we will change
4637 // the following from a discard of the newly-written state to the
4638 // "correct" operation of renaming into the canonical state blob.
4639 mNewStateName.delete(); // TODO: remove; see above comment
4640 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4641
4642 // If this wasn't the PM pseudopackage, tear down the agent side
4643 if (mCurrentPackage.applicationInfo != null) {
4644 // unbind and tidy up even on timeout or failure
4645 try {
4646 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4647
4648 // The agent was probably running with a stub Application object,
4649 // which isn't a valid run mode for the main app logic. Shut
4650 // down the app so that next time it's launched, it gets the
4651 // usual full initialization. Note that this is only done for
4652 // full-system restores: when a single app has requested a restore,
4653 // it is explicitly not killed following that operation.
4654 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4655 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4656 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4657 + mCurrentPackage.applicationInfo.processName);
4658 mActivityManager.killApplicationProcess(
4659 mCurrentPackage.applicationInfo.processName,
4660 mCurrentPackage.applicationInfo.uid);
4661 }
4662 } catch (RemoteException e) {
4663 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004664 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004665 }
Christopher Tate2982d062011-09-06 20:35:24 -07004666
4667 // The caller is responsible for reestablishing the state machine; our
4668 // responsibility here is to clear the decks for whatever comes next.
4669 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4670 synchronized (mCurrentOpLock) {
4671 mCurrentOperations.clear();
4672 }
4673 }
4674
4675 // A call to agent.doRestore() has been positively acknowledged as complete
4676 @Override
4677 public void operationComplete() {
4678 int size = (int) mBackupDataName.length();
4679 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4680 // Just go back to running the restore queue
4681 agentCleanup();
4682
4683 executeNextState(RestoreState.RUNNING_QUEUE);
4684 }
4685
4686 // A call to agent.doRestore() has timed out
4687 @Override
4688 public void handleTimeout() {
4689 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4690 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4691 mCurrentPackage.packageName, "restore timeout");
4692 // Handle like an agent that threw on invocation: wipe it and go on to the next
4693 agentErrorCleanup();
4694 executeNextState(RestoreState.RUNNING_QUEUE);
4695 }
4696
4697 void executeNextState(RestoreState nextState) {
4698 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4699 + this + " nextState=" + nextState);
4700 mCurrentState = nextState;
4701 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4702 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004703 }
4704 }
4705
Christopher Tate44a27902010-01-27 17:15:49 -08004706 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004707 IBackupTransport mTransport;
4708 PackageInfo mPackage;
4709
Christopher Tate44a27902010-01-27 17:15:49 -08004710 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004711 mTransport = transport;
4712 mPackage = packageInfo;
4713 }
4714
Christopher Tateee0e78a2009-07-02 11:17:03 -07004715 public void run() {
4716 try {
4717 // Clear the on-device backup state to ensure a full backup next time
4718 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4719 File stateFile = new File(stateDir, mPackage.packageName);
4720 stateFile.delete();
4721
4722 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004723 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004724 mTransport.clearBackupData(mPackage);
4725 } catch (RemoteException e) {
4726 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004727 } catch (Exception e) {
4728 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004729 } finally {
4730 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004731 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004732 mTransport.finishBackup();
4733 } catch (RemoteException e) {
4734 // can't happen; the transport is local
4735 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004736
4737 // Last but not least, release the cpu
4738 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004739 }
4740 }
4741 }
4742
Christopher Tate44a27902010-01-27 17:15:49 -08004743 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004744 HashSet<String> mQueue;
4745
Christopher Tate44a27902010-01-27 17:15:49 -08004746 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004747 mQueue = transportNames;
4748 }
4749
Christopher Tate4cc86e12009-09-21 19:36:51 -07004750 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004751 try {
4752 for (String transportName : mQueue) {
4753 IBackupTransport transport = getTransport(transportName);
4754 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004755 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004756 continue;
4757 }
4758
Joe Onorato8a9b2202010-02-26 18:56:32 -08004759 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004760 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004761 long startRealtime = SystemClock.elapsedRealtime();
4762 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004763
Christopher Tate4cc86e12009-09-21 19:36:51 -07004764 if (status == BackupConstants.TRANSPORT_OK) {
4765 status = transport.finishBackup();
4766 }
4767
4768 // Okay, the wipe really happened. Clean up our local bookkeeping.
4769 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004770 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004771 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004772 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004773 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004774 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004775 synchronized (mQueueLock) {
4776 recordInitPendingLocked(false, transportName);
4777 }
Dan Egnor726247c2009-09-29 19:12:31 -07004778 } else {
4779 // If this didn't work, requeue this one and try again
4780 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004781 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004782 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004783 synchronized (mQueueLock) {
4784 recordInitPendingLocked(true, transportName);
4785 }
4786 // do this via another alarm to make sure of the wakelock states
4787 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004788 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004789 + transportName + " resched in " + delay);
4790 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4791 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004792 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004793 }
4794 } catch (RemoteException e) {
4795 // can't happen; the transports are local
4796 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004797 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004798 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004799 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004800 mWakelock.release();
4801 }
4802 }
4803 }
4804
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004805 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004806 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004807 dataChangedImpl(packageName, targets);
4808 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004809
Christopher Tatea3d55342012-03-27 13:16:18 -07004810 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004811 // Record that we need a backup pass for the caller. Since multiple callers
4812 // may share a uid, we need to note all candidates within that uid and schedule
4813 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004814 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004815
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004816 if (targets == null) {
4817 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4818 + " uid=" + Binder.getCallingUid());
4819 return;
4820 }
4821
4822 synchronized (mQueueLock) {
4823 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004824 if (targets.contains(packageName)) {
4825 // Add the caller to the set of pending backups. If there is
4826 // one already there, then overwrite it, but no harm done.
4827 BackupRequest req = new BackupRequest(packageName);
4828 if (mPendingBackups.put(packageName, req) == null) {
4829 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004830
Christopher Tatea3d55342012-03-27 13:16:18 -07004831 // Journal this request in case of crash. The put()
4832 // operation returned null when this package was not already
4833 // in the set; we want to avoid touching the disk redundantly.
4834 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004835
Christopher Tatea3d55342012-03-27 13:16:18 -07004836 if (MORE_DEBUG) {
4837 int numKeys = mPendingBackups.size();
4838 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4839 for (BackupRequest b : mPendingBackups.values()) {
4840 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004841 }
4842 }
4843 }
4844 }
4845 }
4846 }
4847
4848 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004849 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004850 // If the caller does not hold the BACKUP permission, it can only request a
4851 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004852 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004853 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004854 synchronized (mBackupParticipants) {
4855 return mBackupParticipants.get(Binder.getCallingUid());
4856 }
4857 }
4858
4859 // a caller with full permission can ask to back up any participating app
4860 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004861 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004862 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004863 int N = mBackupParticipants.size();
4864 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004865 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004866 if (s != null) {
4867 targets.addAll(s);
4868 }
4869 }
4870 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004871 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004872 }
Christopher Tate46758122009-05-06 11:22:00 -07004873
Christopher Tatecde87f42009-06-12 12:55:53 -07004874 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004875 RandomAccessFile out = null;
4876 try {
4877 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4878 out = new RandomAccessFile(mJournal, "rws");
4879 out.seek(out.length());
4880 out.writeUTF(str);
4881 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004882 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004883 mJournal = null;
4884 } finally {
4885 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004886 }
4887 }
4888
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004889 // ----- IBackupManager binder interface -----
4890
4891 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004892 final int callingUserHandle = UserHandle.getCallingUserId();
4893 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004894 // App is running under a non-owner user profile. For now, we do not back
4895 // up data from secondary user profiles.
4896 // TODO: backups for all user profiles.
4897 if (MORE_DEBUG) {
4898 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4899 + callingUserHandle);
4900 }
4901 return;
4902 }
4903
Christopher Tatea3d55342012-03-27 13:16:18 -07004904 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004905 if (targets == null) {
4906 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4907 + " uid=" + Binder.getCallingUid());
4908 return;
4909 }
4910
4911 mBackupHandler.post(new Runnable() {
4912 public void run() {
4913 dataChangedImpl(packageName, targets);
4914 }
4915 });
4916 }
4917
Christopher Tateee0e78a2009-07-02 11:17:03 -07004918 // Clear the given package's backup data from the current transport
4919 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004920 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004921 PackageInfo info;
4922 try {
4923 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4924 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004925 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004926 return;
4927 }
4928
4929 // If the caller does not hold the BACKUP permission, it can only request a
4930 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004931 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004932 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004933 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4934 apps = mBackupParticipants.get(Binder.getCallingUid());
4935 } else {
4936 // a caller with full permission can ask to back up any participating app
4937 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004938 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004939 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004940 int N = mBackupParticipants.size();
4941 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004942 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004943 if (s != null) {
4944 apps.addAll(s);
4945 }
4946 }
4947 }
4948
Christopher Tatea3d55342012-03-27 13:16:18 -07004949 // Is the given app an available participant?
4950 if (apps.contains(packageName)) {
4951 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4952 // found it; fire off the clear request
4953 synchronized (mQueueLock) {
4954 long oldId = Binder.clearCallingIdentity();
4955 mWakelock.acquire();
4956 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4957 new ClearParams(getTransport(mCurrentTransport), info));
4958 mBackupHandler.sendMessage(msg);
4959 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004960 }
4961 }
4962 }
4963
Christopher Tateace7f092009-06-15 18:07:25 -07004964 // Run a backup pass immediately for any applications that have declared
4965 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004966 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004967 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004968
Joe Onorato8a9b2202010-02-26 18:56:32 -08004969 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004970 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004971 // Because the alarms we are using can jitter, and we want an *immediate*
4972 // backup pass to happen, we restart the timer beginning with "next time,"
4973 // then manually fire the backup trigger intent ourselves.
4974 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004975 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004976 mRunBackupIntent.send();
4977 } catch (PendingIntent.CanceledException e) {
4978 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004979 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004980 }
Christopher Tate46758122009-05-06 11:22:00 -07004981 }
4982 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004983
Christopher Tated2c0cd42011-09-15 15:51:29 -07004984 boolean deviceIsProvisioned() {
4985 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07004986 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004987 }
4988
Christopher Tate4a627c72011-04-01 14:43:32 -07004989 // Run a *full* backup pass for the given package, writing the resulting data stream
4990 // to the supplied file descriptor. This method is synchronous and does not return
4991 // to the caller until the backup has been completed.
4992 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004993 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004994 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4995
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004996 final int callingUserHandle = UserHandle.getCallingUserId();
4997 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004998 throw new IllegalStateException("Backup supported only for the device owner");
4999 }
5000
Christopher Tate4a627c72011-04-01 14:43:32 -07005001 // Validate
5002 if (!doAllApps) {
5003 if (!includeShared) {
5004 // If we're backing up shared data (sdcard or equivalent), then we can run
5005 // without any supplied app names. Otherwise, we'd be doing no work, so
5006 // report the error.
5007 if (pkgList == null || pkgList.length == 0) {
5008 throw new IllegalArgumentException(
5009 "Backup requested but neither shared nor any apps named");
5010 }
5011 }
5012 }
5013
Christopher Tate4a627c72011-04-01 14:43:32 -07005014 long oldId = Binder.clearCallingIdentity();
5015 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005016 // Doesn't make sense to do a full backup prior to setup
5017 if (!deviceIsProvisioned()) {
5018 Slog.i(TAG, "Full backup not supported before setup");
5019 return;
5020 }
5021
5022 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5023 + " shared=" + includeShared + " all=" + doAllApps
5024 + " pkgs=" + pkgList);
5025 Slog.i(TAG, "Beginning full backup...");
5026
Christopher Tate4a627c72011-04-01 14:43:32 -07005027 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005028 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005029 final int token = generateToken();
5030 synchronized (mFullConfirmations) {
5031 mFullConfirmations.put(token, params);
5032 }
5033
Christopher Tate75a99702011-05-18 16:28:19 -07005034 // start up the confirmation UI
5035 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5036 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5037 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005038 mFullConfirmations.delete(token);
5039 return;
5040 }
Christopher Tate75a99702011-05-18 16:28:19 -07005041
5042 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005043 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5044
5045 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005046 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005047
5048 // wait for the backup to be performed
5049 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5050 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005051 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005052 try {
5053 fd.close();
5054 } catch (IOException e) {
5055 // just eat it
5056 }
Christopher Tate75a99702011-05-18 16:28:19 -07005057 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005058 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005059 }
Christopher Tate75a99702011-05-18 16:28:19 -07005060 }
5061
5062 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005063 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005064
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005065 final int callingUserHandle = UserHandle.getCallingUserId();
5066 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005067 throw new IllegalStateException("Restore supported only for the device owner");
5068 }
5069
Christopher Tate75a99702011-05-18 16:28:19 -07005070 long oldId = Binder.clearCallingIdentity();
5071
5072 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005073 // Check whether the device has been provisioned -- we don't handle
5074 // full restores prior to completing the setup process.
5075 if (!deviceIsProvisioned()) {
5076 Slog.i(TAG, "Full restore not permitted before setup");
5077 return;
5078 }
5079
5080 Slog.i(TAG, "Beginning full restore...");
5081
Christopher Tate75a99702011-05-18 16:28:19 -07005082 FullRestoreParams params = new FullRestoreParams(fd);
5083 final int token = generateToken();
5084 synchronized (mFullConfirmations) {
5085 mFullConfirmations.put(token, params);
5086 }
5087
5088 // start up the confirmation UI
5089 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5090 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5091 Slog.e(TAG, "Unable to launch full restore confirmation");
5092 mFullConfirmations.delete(token);
5093 return;
5094 }
5095
5096 // make sure the screen is lit for the user interaction
5097 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5098
5099 // start the confirmation countdown
5100 startConfirmationTimeout(token, params);
5101
5102 // wait for the restore to be performed
5103 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5104 waitForCompletion(params);
5105 } finally {
5106 try {
5107 fd.close();
5108 } catch (IOException e) {
5109 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5110 }
5111 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005112 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005113 }
5114 }
5115
5116 boolean startConfirmationUi(int token, String action) {
5117 try {
5118 Intent confIntent = new Intent(action);
5119 confIntent.setClassName("com.android.backupconfirm",
5120 "com.android.backupconfirm.BackupRestoreConfirmation");
5121 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5122 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5123 mContext.startActivity(confIntent);
5124 } catch (ActivityNotFoundException e) {
5125 return false;
5126 }
5127 return true;
5128 }
5129
5130 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005131 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005132 + TIMEOUT_FULL_CONFIRMATION + " millis");
5133 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5134 token, 0, params);
5135 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005136 }
5137
5138 void waitForCompletion(FullParams params) {
5139 synchronized (params.latch) {
5140 while (params.latch.get() == false) {
5141 try {
5142 params.latch.wait();
5143 } catch (InterruptedException e) { /* never interrupted */ }
5144 }
5145 }
5146 }
5147
5148 void signalFullBackupRestoreCompletion(FullParams params) {
5149 synchronized (params.latch) {
5150 params.latch.set(true);
5151 params.latch.notifyAll();
5152 }
5153 }
5154
5155 // Confirm that the previously-requested full backup/restore operation can proceed. This
5156 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005157 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005158 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005159 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005160 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5161 + " allow=" + allow);
5162
5163 // TODO: possibly require not just this signature-only permission, but even
5164 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005165 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005166
5167 long oldId = Binder.clearCallingIdentity();
5168 try {
5169
5170 FullParams params;
5171 synchronized (mFullConfirmations) {
5172 params = mFullConfirmations.get(token);
5173 if (params != null) {
5174 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5175 mFullConfirmations.delete(token);
5176
5177 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005178 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005179 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005180 : MSG_RUN_FULL_RESTORE;
5181
Christopher Tate728a1c42011-07-28 18:03:03 -07005182 params.observer = observer;
5183 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005184
5185 boolean isEncrypted;
5186 try {
5187 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5188 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5189 } catch (RemoteException e) {
5190 // couldn't contact the mount service; fail "safe" and assume encryption
5191 Slog.e(TAG, "Unable to contact mount service!");
5192 isEncrypted = true;
5193 }
5194 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005195
Christopher Tate75a99702011-05-18 16:28:19 -07005196 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005197 mWakelock.acquire();
5198 Message msg = mBackupHandler.obtainMessage(verb, params);
5199 mBackupHandler.sendMessage(msg);
5200 } else {
5201 Slog.w(TAG, "User rejected full backup/restore operation");
5202 // indicate completion without having actually transferred any data
5203 signalFullBackupRestoreCompletion(params);
5204 }
5205 } else {
5206 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5207 }
5208 }
5209 } finally {
5210 Binder.restoreCallingIdentity(oldId);
5211 }
5212 }
5213
Christopher Tate8031a3d2009-07-06 16:36:05 -07005214 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005215 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005217 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005218
Joe Onorato8a9b2202010-02-26 18:56:32 -08005219 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005220
Christopher Tate6ef58a12009-06-29 14:56:28 -07005221 boolean wasEnabled = mEnabled;
5222 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005223 Settings.Secure.putInt(mContext.getContentResolver(),
5224 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005225 mEnabled = enable;
5226 }
5227
Christopher Tate49401dd2009-07-01 12:34:29 -07005228 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005229 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005230 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005231 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005232 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005233 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005234 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005235
Christopher Tateb6787f22009-07-02 17:40:45 -07005236 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005237
5238 // This also constitutes an opt-out, so we wipe any data for
5239 // this device from the backend. We start that process with
5240 // an alarm in order to guarantee wakelock states.
5241 if (wasEnabled && mProvisioned) {
5242 // NOTE: we currently flush every registered transport, not just
5243 // the currently-active one.
5244 HashSet<String> allTransports;
5245 synchronized (mTransports) {
5246 allTransports = new HashSet<String>(mTransports.keySet());
5247 }
5248 // build the set of transports for which we are posting an init
5249 for (String transport : allTransports) {
5250 recordInitPendingLocked(true, transport);
5251 }
5252 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5253 mRunInitIntent);
5254 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005255 }
5256 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005257 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005258
Christopher Tatecce9da52010-02-03 15:11:15 -08005259 // Enable/disable automatic restore of app data at install time
5260 public void setAutoRestore(boolean doAutoRestore) {
5261 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005262 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005263
Joe Onorato8a9b2202010-02-26 18:56:32 -08005264 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005265
5266 synchronized (this) {
5267 Settings.Secure.putInt(mContext.getContentResolver(),
5268 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5269 mAutoRestore = doAutoRestore;
5270 }
5271 }
5272
Christopher Tate8031a3d2009-07-06 16:36:05 -07005273 // Mark the backup service as having been provisioned
5274 public void setBackupProvisioned(boolean available) {
5275 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5276 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005277 /*
5278 * This is now a no-op; provisioning is simply the device's own setup state.
5279 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005280 }
5281
5282 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005283 // We used to use setInexactRepeating(), but that may be linked to
5284 // backups running at :00 more often than not, creating load spikes.
5285 // Schedule at an exact time for now, and also add a bit of "fuzz".
5286
5287 Random random = new Random();
5288 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5289 random.nextInt(FUZZ_MILLIS);
5290 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5291 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005292 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005293 }
5294
Christopher Tate6ef58a12009-06-29 14:56:28 -07005295 // Report whether the backup mechanism is currently enabled
5296 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005297 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005298 return mEnabled; // no need to synchronize just to read it
5299 }
5300
Christopher Tate91717492009-06-26 21:07:13 -07005301 // Report the name of the currently active transport
5302 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005304 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005305 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005306 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005307 }
5308
Christopher Tate91717492009-06-26 21:07:13 -07005309 // Report all known, available backup transports
5310 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005311 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005312
Christopher Tate91717492009-06-26 21:07:13 -07005313 String[] list = null;
5314 ArrayList<String> known = new ArrayList<String>();
5315 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5316 if (entry.getValue() != null) {
5317 known.add(entry.getKey());
5318 }
5319 }
5320
5321 if (known.size() > 0) {
5322 list = new String[known.size()];
5323 known.toArray(list);
5324 }
5325 return list;
5326 }
5327
5328 // Select which transport to use for the next backup operation. If the given
5329 // name is not one of the available transports, no action is taken and the method
5330 // returns null.
5331 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005333
5334 synchronized (mTransports) {
5335 String prevTransport = null;
5336 if (mTransports.get(transport) != null) {
5337 prevTransport = mCurrentTransport;
5338 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005339 Settings.Secure.putString(mContext.getContentResolver(),
5340 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005341 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005342 + " returning " + prevTransport);
5343 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005344 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005345 }
5346 return prevTransport;
5347 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005348 }
5349
Christopher Tatef5e1c292010-12-08 18:40:26 -08005350 // Supply the configuration Intent for the given transport. If the name is not one
5351 // of the available transports, or if the transport does not supply any configuration
5352 // UI, the method returns null.
5353 public Intent getConfigurationIntent(String transportName) {
5354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5355 "getConfigurationIntent");
5356
5357 synchronized (mTransports) {
5358 final IBackupTransport transport = mTransports.get(transportName);
5359 if (transport != null) {
5360 try {
5361 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005362 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005363 + intent);
5364 return intent;
5365 } catch (RemoteException e) {
5366 /* fall through to return null */
5367 }
5368 }
5369 }
5370
5371 return null;
5372 }
5373
5374 // Supply the configuration summary string for the given transport. If the name is
5375 // not one of the available transports, or if the transport does not supply any
5376 // summary / destination string, the method can return null.
5377 //
5378 // This string is used VERBATIM as the summary text of the relevant Settings item!
5379 public String getDestinationString(String transportName) {
5380 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005381 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005382
5383 synchronized (mTransports) {
5384 final IBackupTransport transport = mTransports.get(transportName);
5385 if (transport != null) {
5386 try {
5387 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005388 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005389 return text;
5390 } catch (RemoteException e) {
5391 /* fall through to return null */
5392 }
5393 }
5394 }
5395
5396 return null;
5397 }
5398
Christopher Tate043dadc2009-06-02 16:11:00 -07005399 // Callback: a requested backup agent has been instantiated. This should only
5400 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005401 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005402 synchronized(mAgentConnectLock) {
5403 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005404 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005405 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5406 mConnectedAgent = agent;
5407 mConnecting = false;
5408 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005409 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005410 + " claiming agent connected");
5411 }
5412 mAgentConnectLock.notifyAll();
5413 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005414 }
5415
5416 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5417 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005418 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005419 public void agentDisconnected(String packageName) {
5420 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005421 synchronized(mAgentConnectLock) {
5422 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5423 mConnectedAgent = null;
5424 mConnecting = false;
5425 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005426 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005427 + " claiming agent disconnected");
5428 }
5429 mAgentConnectLock.notifyAll();
5430 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005431 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005432
Christopher Tate1bb69062010-02-19 17:02:12 -08005433 // An application being installed will need a restore pass, then the Package Manager
5434 // will need to be told when the restore is finished.
5435 public void restoreAtInstall(String packageName, int token) {
5436 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005437 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005438 + " attemping install-time restore");
5439 return;
5440 }
5441
5442 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005443 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005444 + " token=" + Integer.toHexString(token)
5445 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005446
Christopher Tatef0872722010-02-25 15:22:48 -08005447 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005448 // okay, we're going to attempt a restore of this package from this restore set.
5449 // The eventual message back into the Package Manager to run the post-install
5450 // steps for 'token' will be issued from the restore handling code.
5451
5452 // We can use a synthetic PackageInfo here because:
5453 // 1. We know it's valid, since the Package Manager supplied the name
5454 // 2. Only the packageName field will be used by the restore code
5455 PackageInfo pkg = new PackageInfo();
5456 pkg.packageName = packageName;
5457
5458 mWakelock.acquire();
5459 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5460 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005461 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005462 mBackupHandler.sendMessage(msg);
5463 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005464 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5465 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005466 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005467 try {
5468 mPackageManagerBinder.finishPackageInstall(token);
5469 } catch (RemoteException e) { /* can't happen */ }
5470 }
5471 }
5472
Christopher Tate8c850b72009-06-07 19:33:20 -07005473 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005474 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5475 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5476 + " transport=" + transport);
5477
5478 boolean needPermission = true;
5479 if (transport == null) {
5480 transport = mCurrentTransport;
5481
5482 if (packageName != null) {
5483 PackageInfo app = null;
5484 try {
5485 app = mPackageManager.getPackageInfo(packageName, 0);
5486 } catch (NameNotFoundException nnf) {
5487 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5488 throw new IllegalArgumentException("Package " + packageName + " not found");
5489 }
5490
5491 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5492 // So: using the current active transport, and the caller has asked
5493 // that its own package will be restored. In this narrow use case
5494 // we do not require the caller to hold the permission.
5495 needPermission = false;
5496 }
5497 }
5498 }
5499
5500 if (needPermission) {
5501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5502 "beginRestoreSession");
5503 } else {
5504 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5505 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005506
5507 synchronized(this) {
5508 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005509 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005510 return null;
5511 }
Chris Tate44ab8452010-11-16 15:10:49 -08005512 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005513 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005514 }
5515 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005516 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005517
Christopher Tate73a3cb32010-12-13 18:27:26 -08005518 void clearRestoreSession(ActiveRestoreSession currentSession) {
5519 synchronized(this) {
5520 if (currentSession != mActiveRestoreSession) {
5521 Slog.e(TAG, "ending non-current restore session");
5522 } else {
5523 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5524 mActiveRestoreSession = null;
5525 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5526 }
5527 }
5528 }
5529
Christopher Tate44a27902010-01-27 17:15:49 -08005530 // Note that a currently-active backup agent has notified us that it has
5531 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005532 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005533 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005534 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5535 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005536 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005537 op = mCurrentOperations.get(token);
5538 if (op != null) {
5539 op.state = OP_ACKNOWLEDGED;
5540 }
Christopher Tate44a27902010-01-27 17:15:49 -08005541 mCurrentOpLock.notifyAll();
5542 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005543
5544 // The completion callback, if any, is invoked on the handler
5545 if (op != null && op.callback != null) {
5546 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5547 mBackupHandler.sendMessage(msg);
5548 }
Christopher Tate44a27902010-01-27 17:15:49 -08005549 }
5550
Christopher Tate9b3905c2009-06-08 15:24:01 -07005551 // ----- Restore session -----
5552
Christopher Tate80202c82010-01-25 19:37:47 -08005553 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005554 private static final String TAG = "RestoreSession";
5555
Chris Tate44ab8452010-11-16 15:10:49 -08005556 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005557 private IBackupTransport mRestoreTransport = null;
5558 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005559 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005560
Chris Tate44ab8452010-11-16 15:10:49 -08005561 ActiveRestoreSession(String packageName, String transport) {
5562 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005563 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005564 }
5565
5566 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005567 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005569 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005570 if (observer == null) {
5571 throw new IllegalArgumentException("Observer must not be null");
5572 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005573
Christopher Tate73a3cb32010-12-13 18:27:26 -08005574 if (mEnded) {
5575 throw new IllegalStateException("Restore session already ended");
5576 }
5577
Christopher Tate1bb69062010-02-19 17:02:12 -08005578 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005579 try {
Christopher Tate43383042009-07-13 15:17:13 -07005580 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005581 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005582 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005583 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005584 // spin off the transport request to our service thread
5585 mWakelock.acquire();
5586 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5587 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5588 mBackupHandler.sendMessage(msg);
5589 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005590 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005591 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005592 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005593 } finally {
5594 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005595 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005596 }
5597
Christopher Tate84725812010-02-04 15:52:40 -08005598 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005599 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5600 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005601
Chris Tate44ab8452010-11-16 15:10:49 -08005602 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005603 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005604
Christopher Tate73a3cb32010-12-13 18:27:26 -08005605 if (mEnded) {
5606 throw new IllegalStateException("Restore session already ended");
5607 }
5608
Dan Egnor0084da52009-07-29 12:57:16 -07005609 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005610 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5611 return -1;
5612 }
5613
5614 if (mPackageName != null) {
5615 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005616 return -1;
5617 }
5618
Christopher Tate21ab6a52009-09-24 18:01:46 -07005619 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005620 for (int i = 0; i < mRestoreSets.length; i++) {
5621 if (token == mRestoreSets[i].token) {
5622 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005623 mWakelock.acquire();
5624 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005625 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005626 mBackupHandler.sendMessage(msg);
5627 Binder.restoreCallingIdentity(oldId);
5628 return 0;
5629 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005630 }
5631 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005632
Joe Onorato8a9b2202010-02-26 18:56:32 -08005633 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005634 return -1;
5635 }
5636
Christopher Tate284f1bb2011-07-07 14:31:18 -07005637 public synchronized int restoreSome(long token, IRestoreObserver observer,
5638 String[] packages) {
5639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5640 "performRestore");
5641
5642 if (DEBUG) {
5643 StringBuilder b = new StringBuilder(128);
5644 b.append("restoreSome token=");
5645 b.append(Long.toHexString(token));
5646 b.append(" observer=");
5647 b.append(observer.toString());
5648 b.append(" packages=");
5649 if (packages == null) {
5650 b.append("null");
5651 } else {
5652 b.append('{');
5653 boolean first = true;
5654 for (String s : packages) {
5655 if (!first) {
5656 b.append(", ");
5657 } else first = false;
5658 b.append(s);
5659 }
5660 b.append('}');
5661 }
5662 Slog.d(TAG, b.toString());
5663 }
5664
5665 if (mEnded) {
5666 throw new IllegalStateException("Restore session already ended");
5667 }
5668
5669 if (mRestoreTransport == null || mRestoreSets == null) {
5670 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5671 return -1;
5672 }
5673
5674 if (mPackageName != null) {
5675 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5676 return -1;
5677 }
5678
5679 synchronized (mQueueLock) {
5680 for (int i = 0; i < mRestoreSets.length; i++) {
5681 if (token == mRestoreSets[i].token) {
5682 long oldId = Binder.clearCallingIdentity();
5683 mWakelock.acquire();
5684 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5685 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5686 packages, true);
5687 mBackupHandler.sendMessage(msg);
5688 Binder.restoreCallingIdentity(oldId);
5689 return 0;
5690 }
5691 }
5692 }
5693
5694 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5695 return -1;
5696 }
5697
Christopher Tate84725812010-02-04 15:52:40 -08005698 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005699 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005700
Christopher Tate73a3cb32010-12-13 18:27:26 -08005701 if (mEnded) {
5702 throw new IllegalStateException("Restore session already ended");
5703 }
5704
Chris Tate44ab8452010-11-16 15:10:49 -08005705 if (mPackageName != null) {
5706 if (! mPackageName.equals(packageName)) {
5707 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5708 + " on session for package " + mPackageName);
5709 return -1;
5710 }
5711 }
5712
Christopher Tate84725812010-02-04 15:52:40 -08005713 PackageInfo app = null;
5714 try {
5715 app = mPackageManager.getPackageInfo(packageName, 0);
5716 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005717 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005718 return -1;
5719 }
5720
5721 // If the caller is not privileged and is not coming from the target
5722 // app's uid, throw a permission exception back to the caller.
5723 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5724 Binder.getCallingPid(), Binder.getCallingUid());
5725 if ((perm == PackageManager.PERMISSION_DENIED) &&
5726 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005727 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005728 + " or calling uid=" + Binder.getCallingUid());
5729 throw new SecurityException("No permission to restore other packages");
5730 }
5731
Christopher Tate7d411a32010-02-26 11:27:08 -08005732 // If the package has no backup agent, we obviously cannot proceed
5733 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005734 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005735 return -1;
5736 }
5737
Christopher Tate84725812010-02-04 15:52:40 -08005738 // So far so good; we're allowed to try to restore this package. Now
5739 // check whether there is data for it in the current dataset, falling back
5740 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005741 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005742
5743 // If we didn't come up with a place to look -- no ancestral dataset and
5744 // the app has never been backed up from this device -- there's nothing
5745 // to do but return failure.
5746 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005747 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005748 return -1;
5749 }
5750
5751 // Ready to go: enqueue the restore request and claim success
5752 long oldId = Binder.clearCallingIdentity();
5753 mWakelock.acquire();
5754 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005755 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005756 mBackupHandler.sendMessage(msg);
5757 Binder.restoreCallingIdentity(oldId);
5758 return 0;
5759 }
5760
Christopher Tate73a3cb32010-12-13 18:27:26 -08005761 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5762 class EndRestoreRunnable implements Runnable {
5763 BackupManagerService mBackupManager;
5764 ActiveRestoreSession mSession;
5765
5766 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5767 mBackupManager = manager;
5768 mSession = session;
5769 }
5770
5771 public void run() {
5772 // clean up the session's bookkeeping
5773 synchronized (mSession) {
5774 try {
5775 if (mSession.mRestoreTransport != null) {
5776 mSession.mRestoreTransport.finishRestore();
5777 }
5778 } catch (Exception e) {
5779 Slog.e(TAG, "Error in finishRestore", e);
5780 } finally {
5781 mSession.mRestoreTransport = null;
5782 mSession.mEnded = true;
5783 }
5784 }
5785
5786 // clean up the BackupManagerService side of the bookkeeping
5787 // and cancel any pending timeout message
5788 mBackupManager.clearRestoreSession(mSession);
5789 }
5790 }
5791
Dan Egnor0084da52009-07-29 12:57:16 -07005792 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005793 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005794
Christopher Tate73a3cb32010-12-13 18:27:26 -08005795 if (mEnded) {
5796 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005797 }
5798
Christopher Tate73a3cb32010-12-13 18:27:26 -08005799 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005800 }
5801 }
5802
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005803 @Override
5804 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005805 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5806
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005807 long identityToken = Binder.clearCallingIdentity();
5808 try {
5809 dumpInternal(pw);
5810 } finally {
5811 Binder.restoreCallingIdentity(identityToken);
5812 }
5813 }
5814
5815 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005816 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005817 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005818 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005819 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005820 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005821 if (mBackupRunning) pw.println("Backup currently running");
5822 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005823 + " (now = " + System.currentTimeMillis() + ')');
5824 pw.println(" next scheduled: " + mNextBackupPass);
5825
Christopher Tate91717492009-06-26 21:07:13 -07005826 pw.println("Available transports:");
5827 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005828 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5829 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005830 IBackupTransport transport = getTransport(t);
5831 File dir = new File(mBaseStateDir, transport.transportDirName());
5832 pw.println(" destination: " + transport.currentDestinationString());
5833 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005834 for (File f : dir.listFiles()) {
5835 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5836 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005837 } catch (Exception e) {
5838 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005839 pw.println(" Error: " + e);
5840 }
Christopher Tate91717492009-06-26 21:07:13 -07005841 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005842
5843 pw.println("Pending init: " + mPendingInits.size());
5844 for (String s : mPendingInits) {
5845 pw.println(" " + s);
5846 }
5847
Christopher Tate6de74ff2012-01-17 15:20:32 -08005848 if (DEBUG_BACKUP_TRACE) {
5849 synchronized (mBackupTrace) {
5850 if (!mBackupTrace.isEmpty()) {
5851 pw.println("Most recent backup trace:");
5852 for (String s : mBackupTrace) {
5853 pw.println(" " + s);
5854 }
5855 }
5856 }
5857 }
5858
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005859 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005860 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005861 for (int i=0; i<N; i++) {
5862 int uid = mBackupParticipants.keyAt(i);
5863 pw.print(" uid: ");
5864 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005865 HashSet<String> participants = mBackupParticipants.valueAt(i);
5866 for (String app: participants) {
5867 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005868 }
5869 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005870
Christopher Tateb49ceb32010-02-08 16:22:24 -08005871 pw.println("Ancestral packages: "
5872 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005873 if (mAncestralPackages != null) {
5874 for (String pkg : mAncestralPackages) {
5875 pw.println(" " + pkg);
5876 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005877 }
5878
Christopher Tate73e02522009-07-15 14:18:26 -07005879 pw.println("Ever backed up: " + mEverStoredApps.size());
5880 for (String pkg : mEverStoredApps) {
5881 pw.println(" " + pkg);
5882 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005883
5884 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005885 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005886 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005887 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005888 }
5889 }
Christopher Tate487529a2009-04-29 14:03:25 -07005890}