blob: 328b503e759d9cbff25e76242a6d3da463b6b2bc [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;
Christopher Tate294b5122013-02-19 14:08:59 -080081import com.android.internal.backup.IObbBackupService;
Jason parksa3cdaa52011-01-13 14:15:43 -060082import com.android.internal.backup.LocalTransport;
83import com.android.server.PackageManagerBackupAgent.Metadata;
84
Christopher Tate2efd2db2011-07-19 16:32:49 -070085import java.io.BufferedInputStream;
86import java.io.BufferedOutputStream;
87import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070088import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070089import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070090import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070091import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070092import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070093import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080094import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070095import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070096import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070097import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070098import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070099import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -0700100import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700101import java.security.InvalidAlgorithmParameterException;
102import java.security.InvalidKeyException;
103import java.security.Key;
104import java.security.NoSuchAlgorithmException;
105import java.security.SecureRandom;
106import java.security.spec.InvalidKeySpecException;
107import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700108import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400109import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700110import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700111import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400112import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700113import java.util.HashSet;
114import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700115import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700116import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800117import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700118import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700119import java.util.zip.Deflater;
120import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700121import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700122
Christopher Tate2efd2db2011-07-19 16:32:49 -0700123import javax.crypto.BadPaddingException;
124import javax.crypto.Cipher;
125import javax.crypto.CipherInputStream;
126import javax.crypto.CipherOutputStream;
127import javax.crypto.IllegalBlockSizeException;
128import javax.crypto.NoSuchPaddingException;
129import javax.crypto.SecretKey;
130import javax.crypto.SecretKeyFactory;
131import javax.crypto.spec.IvParameterSpec;
132import javax.crypto.spec.PBEKeySpec;
133import javax.crypto.spec.SecretKeySpec;
134
Christopher Tate487529a2009-04-29 14:03:25 -0700135class BackupManagerService extends IBackupManager.Stub {
136 private static final String TAG = "BackupManagerService";
Christopher Tate559c6542013-02-12 14:57:04 -0800137 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700138 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700139
140 // Name and current contents version of the full-backup manifest file
141 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
142 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700143 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
144 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700145 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700146
Christopher Tate73d73692012-01-20 17:11:31 -0800147 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
148
Christopher Tate49401dd2009-07-01 12:34:29 -0700149 // How often we perform a backup pass. Privileged external callers can
150 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700151 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700152
Dan Egnorc1c49c02009-10-30 17:35:39 -0700153 // Random variation in backup scheduling time to avoid server load spikes
154 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
155
Christopher Tate8031a3d2009-07-06 16:36:05 -0700156 // The amount of time between the initial provisioning of the device and
157 // the first backup pass.
158 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
159
Christopher Tate45281862010-03-05 15:46:30 -0800160 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
161 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
162 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700163 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700164 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700165 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700166 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700167 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700168 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
169 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800170 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700171 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
172 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700173
Christopher Tate8e294d42011-08-31 20:37:12 -0700174 // backup task state machine tick
175 static final int MSG_BACKUP_RESTORE_STEP = 20;
176 static final int MSG_OP_COMPLETE = 21;
177
Christopher Tatec7b31e32009-06-10 15:49:30 -0700178 // Timeout interval for deciding that a bind or clear-data has taken too long
179 static final long TIMEOUT_INTERVAL = 10 * 1000;
180
Christopher Tate44a27902010-01-27 17:15:49 -0800181 // Timeout intervals for agent backup & restore operations
182 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700183 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700184 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800185 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
186
Christopher Tate2efd2db2011-07-19 16:32:49 -0700187 // User confirmation timeout for a full backup/restore operation. It's this long in
188 // order to give them time to enter the backup password.
189 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700190
Christopher Tate487529a2009-04-29 14:03:25 -0700191 private Context mContext;
192 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800193 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700194 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700195 private PowerManager mPowerManager;
196 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700197 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800198 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700199
Christopher Tate73e02522009-07-15 14:18:26 -0700200 boolean mEnabled; // access to this is synchronized on 'this'
201 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800202 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700203 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800204 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800205 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700206 PendingIntent mRunBackupIntent, mRunInitIntent;
207 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700208 // map UIDs to the set of participating packages under that UID
209 final SparseArray<HashSet<String>> mBackupParticipants
210 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700211 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700212 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700213 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700214
Christopher Tatecc55f812011-08-16 16:06:53 -0700215 BackupRequest(String pkgName) {
216 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700217 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700218
219 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700220 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700221 }
Christopher Tate46758122009-05-06 11:22:00 -0700222 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800223 // Backups that we haven't started yet. Keys are package names.
224 HashMap<String,BackupRequest> mPendingBackups
225 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700226
227 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700228 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700229
230 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700231 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700232
Christopher Tate043dadc2009-06-02 16:11:00 -0700233 // The thread performing the sequence of queued backups binds to each app's agent
234 // in succession. Bind notifications are asynchronously delivered through the
235 // Activity Manager; use this lock object to signal when a requested binding has
236 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700237 final Object mAgentConnectLock = new Object();
238 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700239 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700240 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700241 volatile long mLastBackupPass;
242 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700243
Christopher Tate6de74ff2012-01-17 15:20:32 -0800244 // For debugging, we maintain a progress trace of operations during backup
245 static final boolean DEBUG_BACKUP_TRACE = true;
246 final List<String> mBackupTrace = new ArrayList<String>();
247
Christopher Tate55f931a2009-09-29 17:17:34 -0700248 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700249 final Object mClearDataLock = new Object();
250 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700251
Christopher Tate91717492009-06-26 21:07:13 -0700252 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700253 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700254 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700255 String mCurrentTransport;
256 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800257 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700258
Christopher Tate97ea1222012-05-17 14:59:41 -0700259 // Watch the device provisioning operation during setup
260 ContentObserver mProvisionedObserver;
261
262 class ProvisionedObserver extends ContentObserver {
263 public ProvisionedObserver(Handler handler) {
264 super(handler);
265 }
266
267 public void onChange(boolean selfChange) {
268 final boolean wasProvisioned = mProvisioned;
269 final boolean isProvisioned = deviceIsProvisioned();
270 // latch: never unprovision
271 mProvisioned = wasProvisioned || isProvisioned;
272 if (MORE_DEBUG) {
273 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
274 + " is=" + isProvisioned + " now=" + mProvisioned);
275 }
276
277 synchronized (mQueueLock) {
278 if (mProvisioned && !wasProvisioned && mEnabled) {
279 // we're now good to go, so start the backup alarms
280 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
281 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
282 }
283 }
284 }
285 }
286
Christopher Tate2d449afe2010-03-29 19:14:24 -0700287 class RestoreGetSetsParams {
288 public IBackupTransport transport;
289 public ActiveRestoreSession session;
290 public IRestoreObserver observer;
291
292 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
293 IRestoreObserver _observer) {
294 transport = _transport;
295 session = _session;
296 observer = _observer;
297 }
298 }
299
Christopher Tate73e02522009-07-15 14:18:26 -0700300 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700301 public IBackupTransport transport;
302 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700303 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800304 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800305 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700306 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700307 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800308
309 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700310 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800311 transport = _transport;
312 observer = _obs;
313 token = _token;
314 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800315 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700316 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700317 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800318 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700319
Chris Tate249345b2010-10-29 12:57:04 -0700320 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
321 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700322 transport = _transport;
323 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700324 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800325 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800326 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700327 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700328 filterSet = null;
329 }
330
331 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
332 String[] _filterSet, boolean _needFullBackup) {
333 transport = _transport;
334 observer = _obs;
335 token = _token;
336 pkgInfo = null;
337 pmToken = 0;
338 needFullBackup = _needFullBackup;
339 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700340 }
341 }
342
Christopher Tate73e02522009-07-15 14:18:26 -0700343 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700344 public IBackupTransport transport;
345 public PackageInfo packageInfo;
346
347 ClearParams(IBackupTransport _transport, PackageInfo _info) {
348 transport = _transport;
349 packageInfo = _info;
350 }
351 }
352
Christopher Tate4a627c72011-04-01 14:43:32 -0700353 class FullParams {
354 public ParcelFileDescriptor fd;
355 public final AtomicBoolean latch;
356 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700357 public String curPassword; // filled in by the confirmation step
358 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700359
360 FullParams() {
361 latch = new AtomicBoolean(false);
362 }
363 }
364
365 class FullBackupParams extends FullParams {
366 public boolean includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -0800367 public boolean includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -0700368 public boolean includeShared;
369 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700370 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700371 public String[] packages;
372
Christopher Tate294b5122013-02-19 14:08:59 -0800373 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
374 boolean saveShared, boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700375 fd = output;
376 includeApks = saveApks;
Christopher Tate294b5122013-02-19 14:08:59 -0800377 includeObbs = saveObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -0700378 includeShared = saveShared;
379 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700380 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700381 packages = pkgList;
382 }
383 }
384
385 class FullRestoreParams extends FullParams {
386 FullRestoreParams(ParcelFileDescriptor input) {
387 fd = input;
388 }
389 }
390
Christopher Tate44a27902010-01-27 17:15:49 -0800391 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
392 // token is the index of the entry in the pending-operations list.
393 static final int OP_PENDING = 0;
394 static final int OP_ACKNOWLEDGED = 1;
395 static final int OP_TIMEOUT = -1;
396
Christopher Tate8e294d42011-08-31 20:37:12 -0700397 class Operation {
398 public int state;
399 public BackupRestoreTask callback;
400
401 Operation(int initialState, BackupRestoreTask callbackObj) {
402 state = initialState;
403 callback = callbackObj;
404 }
405 }
406 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800407 final Object mCurrentOpLock = new Object();
408 final Random mTokenGenerator = new Random();
409
Christopher Tate4a627c72011-04-01 14:43:32 -0700410 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
411
Christopher Tate5cb400b2009-06-25 16:03:14 -0700412 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700413 File mBaseStateDir;
414 File mDataDir;
415 File mJournalDir;
416 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700417
Christopher Tate2efd2db2011-07-19 16:32:49 -0700418 // Backup password, if any, and the file where it's saved. What is stored is not the
419 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
420 // persisted) salt. Validation is performed by running the challenge text through the
421 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
422 // the saved hash string, then the challenge text matches the originally supplied
423 // password text.
424 private final SecureRandom mRng = new SecureRandom();
425 private String mPasswordHash;
426 private File mPasswordHashFile;
427 private byte[] mPasswordSalt;
428
429 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
430 static final int PBKDF2_HASH_ROUNDS = 10000;
431 static final int PBKDF2_KEY_SIZE = 256; // bits
432 static final int PBKDF2_SALT_SIZE = 512; // bits
433 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
434
Christopher Tate84725812010-02-04 15:52:40 -0800435 // Keep a log of all the apps we've ever backed up, and what the
436 // dataset tokens are for both the current backup dataset and
437 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700438 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700439 HashSet<String> mEverStoredApps = new HashSet<String>();
440
Christopher Tateb49ceb32010-02-08 16:22:24 -0800441 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800442 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800443 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800444 long mAncestralToken = 0;
445 long mCurrentToken = 0;
446
Christopher Tate4cc86e12009-09-21 19:36:51 -0700447 // Persistently track the need to do a full init
448 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
449 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700450
Christopher Tate4a627c72011-04-01 14:43:32 -0700451 // Utility: build a new random integer token
452 int generateToken() {
453 int token;
454 do {
455 synchronized (mTokenGenerator) {
456 token = mTokenGenerator.nextInt();
457 }
458 } while (token < 0);
459 return token;
460 }
461
Christopher Tate44a27902010-01-27 17:15:49 -0800462 // ----- Asynchronous backup/restore handler thread -----
463
464 private class BackupHandler extends Handler {
465 public BackupHandler(Looper looper) {
466 super(looper);
467 }
468
469 public void handleMessage(Message msg) {
470
471 switch (msg.what) {
472 case MSG_RUN_BACKUP:
473 {
474 mLastBackupPass = System.currentTimeMillis();
475 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
476
477 IBackupTransport transport = getTransport(mCurrentTransport);
478 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800479 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700480 synchronized (mQueueLock) {
481 mBackupRunning = false;
482 }
Christopher Tate44a27902010-01-27 17:15:49 -0800483 mWakelock.release();
484 break;
485 }
486
487 // snapshot the pending-backup set and work on that
488 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800489 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800490 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800491 // Do we have any work to do? Construct the work queue
492 // then release the synchronization lock to actually run
493 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800494 if (mPendingBackups.size() > 0) {
495 for (BackupRequest b: mPendingBackups.values()) {
496 queue.add(b);
497 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800498 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800499 mPendingBackups.clear();
500
501 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800502 mJournal = null;
503
Christopher Tate44a27902010-01-27 17:15:49 -0800504 }
505 }
Christopher Tatec61da312010-02-05 10:41:27 -0800506
Christopher Tate8e294d42011-08-31 20:37:12 -0700507 // At this point, we have started a new journal file, and the old
508 // file identity is being passed to the backup processing task.
509 // When it completes successfully, that old journal file will be
510 // deleted. If we crash prior to that, the old journal is parsed
511 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800512 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700513 // Spin up a backup state sequence and set it running
514 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
515 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
516 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800517 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800518 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700519 synchronized (mQueueLock) {
520 mBackupRunning = false;
521 }
Christopher Tatec61da312010-02-05 10:41:27 -0800522 mWakelock.release();
523 }
Christopher Tate44a27902010-01-27 17:15:49 -0800524 break;
525 }
526
Christopher Tate8e294d42011-08-31 20:37:12 -0700527 case MSG_BACKUP_RESTORE_STEP:
528 {
529 try {
530 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
531 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
532 task.execute();
533 } catch (ClassCastException e) {
534 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
535 }
536 break;
537 }
538
539 case MSG_OP_COMPLETE:
540 {
541 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700542 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
543 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700544 } catch (ClassCastException e) {
545 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
546 }
547 break;
548 }
549
Christopher Tate44a27902010-01-27 17:15:49 -0800550 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700551 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700552 // TODO: refactor full backup to be a looper-based state machine
553 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700554 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700555 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
Christopher Tate294b5122013-02-19 14:08:59 -0800556 params.observer, params.includeApks, params.includeObbs,
Christopher Tate728a1c42011-07-28 18:03:03 -0700557 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700558 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700559 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800560 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700561 }
Christopher Tate44a27902010-01-27 17:15:49 -0800562
563 case MSG_RUN_RESTORE:
564 {
565 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800566 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700567 PerformRestoreTask task = new PerformRestoreTask(
568 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700569 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700570 params.needFullBackup, params.filterSet);
571 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
572 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800573 break;
574 }
575
Christopher Tate75a99702011-05-18 16:28:19 -0700576 case MSG_RUN_FULL_RESTORE:
577 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700578 // TODO: refactor full restore to be a looper-based state machine
579 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700580 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700581 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
582 params.curPassword, params.encryptPassword,
583 params.observer, params.latch);
584 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700585 break;
586 }
587
Christopher Tate44a27902010-01-27 17:15:49 -0800588 case MSG_RUN_CLEAR:
589 {
590 ClearParams params = (ClearParams)msg.obj;
591 (new PerformClearTask(params.transport, params.packageInfo)).run();
592 break;
593 }
594
595 case MSG_RUN_INITIALIZE:
596 {
597 HashSet<String> queue;
598
599 // Snapshot the pending-init queue and work on that
600 synchronized (mQueueLock) {
601 queue = new HashSet<String>(mPendingInits);
602 mPendingInits.clear();
603 }
604
605 (new PerformInitializeTask(queue)).run();
606 break;
607 }
608
Christopher Tate2d449afe2010-03-29 19:14:24 -0700609 case MSG_RUN_GET_RESTORE_SETS:
610 {
611 // Like other async operations, this is entered with the wakelock held
612 RestoreSet[] sets = null;
613 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
614 try {
615 sets = params.transport.getAvailableRestoreSets();
616 // cache the result in the active session
617 synchronized (params.session) {
618 params.session.mRestoreSets = sets;
619 }
620 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
621 } catch (Exception e) {
622 Slog.e(TAG, "Error from transport getting set list");
623 } finally {
624 if (params.observer != null) {
625 try {
626 params.observer.restoreSetsAvailable(sets);
627 } catch (RemoteException re) {
628 Slog.e(TAG, "Unable to report listing to observer");
629 } catch (Exception e) {
630 Slog.e(TAG, "Restore observer threw", e);
631 }
632 }
633
Christopher Tate2a935092011-03-03 17:30:32 -0800634 // Done: reset the session timeout clock
635 removeMessages(MSG_RESTORE_TIMEOUT);
636 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
637
Christopher Tate2d449afe2010-03-29 19:14:24 -0700638 mWakelock.release();
639 }
640 break;
641 }
642
Christopher Tate44a27902010-01-27 17:15:49 -0800643 case MSG_TIMEOUT:
644 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700645 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800646 break;
647 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800648
649 case MSG_RESTORE_TIMEOUT:
650 {
651 synchronized (BackupManagerService.this) {
652 if (mActiveRestoreSession != null) {
653 // Client app left the restore session dangling. We know that it
654 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700655 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800656 // up now.
657 Slog.w(TAG, "Restore session timed out; aborting");
658 post(mActiveRestoreSession.new EndRestoreRunnable(
659 BackupManagerService.this, mActiveRestoreSession));
660 }
661 }
662 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700663
664 case MSG_FULL_CONFIRMATION_TIMEOUT:
665 {
666 synchronized (mFullConfirmations) {
667 FullParams params = mFullConfirmations.get(msg.arg1);
668 if (params != null) {
669 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
670
671 // Release the waiter; timeout == completion
672 signalFullBackupRestoreCompletion(params);
673
674 // Remove the token from the set
675 mFullConfirmations.delete(msg.arg1);
676
677 // Report a timeout to the observer, if any
678 if (params.observer != null) {
679 try {
680 params.observer.onTimeout();
681 } catch (RemoteException e) {
682 /* don't care if the app has gone away */
683 }
684 }
685 } else {
686 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
687 }
688 }
689 break;
690 }
Christopher Tate44a27902010-01-27 17:15:49 -0800691 }
692 }
693 }
694
Christopher Tate6de74ff2012-01-17 15:20:32 -0800695 // ----- Debug-only backup operation trace -----
696 void addBackupTrace(String s) {
697 if (DEBUG_BACKUP_TRACE) {
698 synchronized (mBackupTrace) {
699 mBackupTrace.add(s);
700 }
701 }
702 }
703
704 void clearBackupTrace() {
705 if (DEBUG_BACKUP_TRACE) {
706 synchronized (mBackupTrace) {
707 mBackupTrace.clear();
708 }
709 }
710 }
711
Christopher Tate44a27902010-01-27 17:15:49 -0800712 // ----- Main service implementation -----
713
Christopher Tate487529a2009-04-29 14:03:25 -0700714 public BackupManagerService(Context context) {
715 mContext = context;
716 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700717 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700718 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700719
Christopher Tateb6787f22009-07-02 17:40:45 -0700720 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
721 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700722 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700723
Christopher Tate44a27902010-01-27 17:15:49 -0800724 mBackupManagerBinder = asInterface(asBinder());
725
726 // spin up the backup/restore handler thread
727 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
728 mHandlerThread.start();
729 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
730
Christopher Tate22b87872009-05-04 16:41:53 -0700731 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700732 final ContentResolver resolver = context.getContentResolver();
733 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700734 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700735 mProvisioned = Settings.Global.getInt(resolver,
736 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700737 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800738 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700739
740 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
741 resolver.registerContentObserver(
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700742 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
Christopher Tate97ea1222012-05-17 14:59:41 -0700743 false, mProvisionedObserver);
744
Oscar Montemayora8529f62009-11-18 10:14:20 -0800745 // If Encrypted file systems is enabled or disabled, this call will return the
746 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600747 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800748 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700749 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700750
Christopher Tate2efd2db2011-07-19 16:32:49 -0700751 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
752 if (mPasswordHashFile.exists()) {
753 FileInputStream fin = null;
754 DataInputStream in = null;
755 try {
756 fin = new FileInputStream(mPasswordHashFile);
757 in = new DataInputStream(new BufferedInputStream(fin));
758 // integer length of the salt array, followed by the salt,
759 // then the hex pw hash string
760 int saltLen = in.readInt();
761 byte[] salt = new byte[saltLen];
762 in.readFully(salt);
763 mPasswordHash = in.readUTF();
764 mPasswordSalt = salt;
765 } catch (IOException e) {
766 Slog.e(TAG, "Unable to read saved backup pw hash");
767 } finally {
768 try {
769 if (in != null) in.close();
770 if (fin != null) fin.close();
771 } catch (IOException e) {
772 Slog.w(TAG, "Unable to close streams");
773 }
774 }
775 }
776
Christopher Tate4cc86e12009-09-21 19:36:51 -0700777 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700778 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700779 IntentFilter filter = new IntentFilter();
780 filter.addAction(RUN_BACKUP_ACTION);
781 context.registerReceiver(mRunBackupReceiver, filter,
782 android.Manifest.permission.BACKUP, null);
783
784 mRunInitReceiver = new RunInitializeReceiver();
785 filter = new IntentFilter();
786 filter.addAction(RUN_INITIALIZE_ACTION);
787 context.registerReceiver(mRunInitReceiver, filter,
788 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700789
790 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700791 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
792 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
793
Christopher Tate4cc86e12009-09-21 19:36:51 -0700794 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
795 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
796 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
797
Christopher Tatecde87f42009-06-12 12:55:53 -0700798 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700799 mJournalDir = new File(mBaseStateDir, "pending");
800 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700801 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700802
Christopher Tate73e02522009-07-15 14:18:26 -0700803 // Set up the various sorts of package tracking we do
804 initPackageTracking();
805
Christopher Tateabce4e82009-06-18 18:35:32 -0700806 // Build our mapping of uid to backup client services. This implicitly
807 // schedules a backup pass on the Package Manager metadata the first
808 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700809 synchronized (mBackupParticipants) {
810 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700811 }
812
Dan Egnor87a02bc2009-06-17 02:30:10 -0700813 // Set up our transport options and initialize the default transport
814 // TODO: Have transports register themselves somehow?
815 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700816 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700817 ComponentName localName = new ComponentName(context, LocalTransport.class);
818 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700819
Christopher Tate91717492009-06-26 21:07:13 -0700820 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700821 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
822 Settings.Secure.BACKUP_TRANSPORT);
823 if ("".equals(mCurrentTransport)) {
824 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700825 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800826 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700827
828 // Attach to the Google backup transport. When this comes up, it will set
829 // itself as the current transport because we explicitly reset mCurrentTransport
830 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700831 ComponentName transportComponent = new ComponentName("com.google.android.backup",
832 "com.google.android.backup.BackupTransportService");
833 try {
834 // If there's something out there that is supposed to be the Google
835 // backup transport, make sure it's legitimately part of the OS build
836 // and not an app lying about its package name.
837 ApplicationInfo info = mPackageManager.getApplicationInfo(
838 transportComponent.getPackageName(), 0);
839 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
840 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
841 Intent intent = new Intent().setComponent(transportComponent);
Amith Yamasani27b89e62013-01-16 12:30:11 -0800842 context.bindServiceAsUser(intent, mGoogleConnection, Context.BIND_AUTO_CREATE,
843 UserHandle.OWNER);
Christopher Tatea32504f2010-04-21 17:58:07 -0700844 } else {
845 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
846 }
847 } catch (PackageManager.NameNotFoundException nnf) {
848 // No such package? No binding.
849 if (DEBUG) Slog.v(TAG, "Google transport not present");
850 }
Christopher Tateaa088442009-06-16 18:25:46 -0700851
Christopher Tatecde87f42009-06-12 12:55:53 -0700852 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700853 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700854 parseLeftoverJournals();
855
Christopher Tateb6787f22009-07-02 17:40:45 -0700856 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700857 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700858
859 // Start the backup passes going
860 setBackupEnabled(areEnabled);
861 }
862
863 private class RunBackupReceiver extends BroadcastReceiver {
864 public void onReceive(Context context, Intent intent) {
865 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700866 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700867 if (mPendingInits.size() > 0) {
868 // If there are pending init operations, we process those
869 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800870 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700871 try {
872 mAlarmManager.cancel(mRunInitIntent);
873 mRunInitIntent.send();
874 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800875 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700876 // can't really do more than bail here
877 }
878 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800879 // Don't run backups now if we're disabled or not yet
880 // fully set up.
881 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700882 if (!mBackupRunning) {
883 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700884
Christopher Tate336a6492011-10-05 16:05:43 -0700885 // Acquire the wakelock and pass it to the backup thread. it will
886 // be released once backup concludes.
887 mBackupRunning = true;
888 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700889
Christopher Tate336a6492011-10-05 16:05:43 -0700890 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
891 mBackupHandler.sendMessage(msg);
892 } else {
893 Slog.i(TAG, "Backup time but one already running");
894 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700895 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800896 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700897 }
898 }
899 }
900 }
901 }
902 }
903
904 private class RunInitializeReceiver extends BroadcastReceiver {
905 public void onReceive(Context context, Intent intent) {
906 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
907 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700909
910 // Acquire the wakelock and pass it to the init thread. it will
911 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700912 mWakelock.acquire();
913
Christopher Tate4cc86e12009-09-21 19:36:51 -0700914 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700915 mBackupHandler.sendMessage(msg);
916 }
917 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700918 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700919 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700920
Christopher Tate73e02522009-07-15 14:18:26 -0700921 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800922 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700923
Christopher Tate84725812010-02-04 15:52:40 -0800924 // Remember our ancestral dataset
925 mTokenFile = new File(mBaseStateDir, "ancestral");
926 try {
927 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800928 int version = tf.readInt();
929 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
930 mAncestralToken = tf.readLong();
931 mCurrentToken = tf.readLong();
932
933 int numPackages = tf.readInt();
934 if (numPackages >= 0) {
935 mAncestralPackages = new HashSet<String>();
936 for (int i = 0; i < numPackages; i++) {
937 String pkgName = tf.readUTF();
938 mAncestralPackages.add(pkgName);
939 }
940 }
941 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800942 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800943 } catch (FileNotFoundException fnf) {
944 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800945 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800946 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800947 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800948 }
949
Christopher Tatee97e8072009-07-15 16:45:50 -0700950 // Keep a log of what apps we've ever backed up. Because we might have
951 // rebooted in the middle of an operation that was removing something from
952 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700953 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700954 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700955
Christopher Tatee97e8072009-07-15 16:45:50 -0700956 // If we were in the middle of removing something from the ever-backed-up
957 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700958 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700959 if (tempProcessedFile.exists()) {
960 tempProcessedFile.delete();
961 }
962
Dan Egnor852f8e42009-09-30 11:20:45 -0700963 // If there are previous contents, parse them out then start a new
964 // file to continue the recordkeeping.
965 if (mEverStored.exists()) {
966 RandomAccessFile temp = null;
967 RandomAccessFile in = null;
968
969 try {
970 temp = new RandomAccessFile(tempProcessedFile, "rws");
971 in = new RandomAccessFile(mEverStored, "r");
972
973 while (true) {
974 PackageInfo info;
975 String pkg = in.readUTF();
976 try {
977 info = mPackageManager.getPackageInfo(pkg, 0);
978 mEverStoredApps.add(pkg);
979 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700980 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700981 } catch (NameNotFoundException e) {
982 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700983 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700984 }
985 }
986 } catch (EOFException e) {
987 // Once we've rewritten the backup history log, atomically replace the
988 // old one with the new one then reopen the file for continuing use.
989 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800990 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700991 }
992 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800993 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700994 } finally {
995 try { if (temp != null) temp.close(); } catch (IOException e) {}
996 try { if (in != null) in.close(); } catch (IOException e) {}
997 }
998 }
999
Christopher Tate73e02522009-07-15 14:18:26 -07001000 // Register for broadcasts about package install, etc., so we can
1001 // update the provider list.
1002 IntentFilter filter = new IntentFilter();
1003 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1004 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1005 filter.addDataScheme("package");
1006 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001007 // Register for events related to sdcard installation.
1008 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001009 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1010 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001011 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001012 }
1013
Christopher Tatecde87f42009-06-12 12:55:53 -07001014 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001015 for (File f : mJournalDir.listFiles()) {
1016 if (mJournal == null || f.compareTo(mJournal) != 0) {
1017 // This isn't the current journal, so it must be a leftover. Read
1018 // out the package names mentioned there and schedule them for
1019 // backup.
1020 RandomAccessFile in = null;
1021 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001022 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001023 in = new RandomAccessFile(f, "r");
1024 while (true) {
1025 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001026 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001027 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001028 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001029 } catch (EOFException e) {
1030 // no more data; we're done
1031 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001032 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001033 } finally {
1034 // close/delete the file
1035 try { if (in != null) in.close(); } catch (IOException e) {}
1036 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001037 }
1038 }
1039 }
1040 }
1041
Christopher Tate2efd2db2011-07-19 16:32:49 -07001042 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1043 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1044 }
1045
1046 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1047 try {
1048 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1049 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1050 return keyFactory.generateSecret(ks);
1051 } catch (InvalidKeySpecException e) {
1052 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1053 } catch (NoSuchAlgorithmException e) {
1054 Slog.e(TAG, "PBKDF2 unavailable!");
1055 }
1056 return null;
1057 }
1058
1059 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1060 SecretKey key = buildPasswordKey(pw, salt, rounds);
1061 if (key != null) {
1062 return byteArrayToHex(key.getEncoded());
1063 }
1064 return null;
1065 }
1066
1067 private String byteArrayToHex(byte[] data) {
1068 StringBuilder buf = new StringBuilder(data.length * 2);
1069 for (int i = 0; i < data.length; i++) {
1070 buf.append(Byte.toHexString(data[i], true));
1071 }
1072 return buf.toString();
1073 }
1074
1075 private byte[] hexToByteArray(String digits) {
1076 final int bytes = digits.length() / 2;
1077 if (2*bytes != digits.length()) {
1078 throw new IllegalArgumentException("Hex string must have an even number of digits");
1079 }
1080
1081 byte[] result = new byte[bytes];
1082 for (int i = 0; i < digits.length(); i += 2) {
1083 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1084 }
1085 return result;
1086 }
1087
1088 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1089 char[] mkAsChar = new char[pwBytes.length];
1090 for (int i = 0; i < pwBytes.length; i++) {
1091 mkAsChar[i] = (char) pwBytes[i];
1092 }
1093
1094 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1095 return checksum.getEncoded();
1096 }
1097
1098 // Used for generating random salts or passwords
1099 private byte[] randomBytes(int bits) {
1100 byte[] array = new byte[bits / 8];
1101 mRng.nextBytes(array);
1102 return array;
1103 }
1104
1105 // Backup password management
1106 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001107 // First, on an encrypted device we require matching the device pw
1108 final boolean isEncrypted;
1109 try {
1110 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1111 if (isEncrypted) {
1112 if (DEBUG) {
1113 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1114 }
1115 // 0 means the password validated
1116 // -2 means device not encrypted
1117 // Any other result is either password failure or an error condition,
1118 // so we refuse the match
1119 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1120 if (result == 0) {
1121 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1122 return true;
1123 } else if (result != -2) {
1124 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1125 return false;
1126 } else {
1127 // ...else the device is supposedly not encrypted. HOWEVER, the
1128 // query about the encryption state said that the device *is*
1129 // encrypted, so ... we may have a problem. Log it and refuse
1130 // the backup.
1131 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1132 return false;
1133 }
1134 }
1135 } catch (Exception e) {
1136 // Something went wrong talking to the mount service. This is very bad;
1137 // assume that we fail password validation.
1138 return false;
1139 }
1140
Christopher Tate2efd2db2011-07-19 16:32:49 -07001141 if (mPasswordHash == null) {
1142 // no current password case -- require that 'currentPw' be null or empty
1143 if (candidatePw == null || "".equals(candidatePw)) {
1144 return true;
1145 } // else the non-empty candidate does not match the empty stored pw
1146 } else {
1147 // hash the stated current pw and compare to the stored one
1148 if (candidatePw != null && candidatePw.length() > 0) {
1149 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1150 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1151 // candidate hash matches the stored hash -- the password matches
1152 return true;
1153 }
1154 } // else the stored pw is nonempty but the candidate is empty; no match
1155 }
1156 return false;
1157 }
1158
1159 @Override
1160 public boolean setBackupPassword(String currentPw, String newPw) {
1161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1162 "setBackupPassword");
1163
1164 // If the supplied pw doesn't hash to the the saved one, fail
1165 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1166 return false;
1167 }
1168
1169 // Clearing the password is okay
1170 if (newPw == null || newPw.isEmpty()) {
1171 if (mPasswordHashFile.exists()) {
1172 if (!mPasswordHashFile.delete()) {
1173 // Unable to delete the old pw file, so fail
1174 Slog.e(TAG, "Unable to clear backup password");
1175 return false;
1176 }
1177 }
1178 mPasswordHash = null;
1179 mPasswordSalt = null;
1180 return true;
1181 }
1182
1183 try {
1184 // Okay, build the hash of the new backup password
1185 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1186 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1187
1188 OutputStream pwf = null, buffer = null;
1189 DataOutputStream out = null;
1190 try {
1191 pwf = new FileOutputStream(mPasswordHashFile);
1192 buffer = new BufferedOutputStream(pwf);
1193 out = new DataOutputStream(buffer);
1194 // integer length of the salt array, followed by the salt,
1195 // then the hex pw hash string
1196 out.writeInt(salt.length);
1197 out.write(salt);
1198 out.writeUTF(newPwHash);
1199 out.flush();
1200 mPasswordHash = newPwHash;
1201 mPasswordSalt = salt;
1202 return true;
1203 } finally {
1204 if (out != null) out.close();
1205 if (buffer != null) buffer.close();
1206 if (pwf != null) pwf.close();
1207 }
1208 } catch (IOException e) {
1209 Slog.e(TAG, "Unable to set backup password");
1210 }
1211 return false;
1212 }
1213
1214 @Override
1215 public boolean hasBackupPassword() {
1216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1217 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001218
1219 try {
1220 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1221 || (mPasswordHash != null && mPasswordHash.length() > 0);
1222 } catch (Exception e) {
1223 // If we can't talk to the mount service we have a serious problem; fail
1224 // "secure" i.e. assuming that we require a password
1225 return true;
1226 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001227 }
1228
Christopher Tate4cc86e12009-09-21 19:36:51 -07001229 // Maintain persistent state around whether need to do an initialize operation.
1230 // Must be called with the queue lock held.
1231 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001232 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001233 + " on transport " + transportName);
1234 try {
1235 IBackupTransport transport = getTransport(transportName);
1236 String transportDirName = transport.transportDirName();
1237 File stateDir = new File(mBaseStateDir, transportDirName);
1238 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1239
1240 if (isPending) {
1241 // We need an init before we can proceed with sending backup data.
1242 // Record that with an entry in our set of pending inits, as well as
1243 // journaling it via creation of a sentinel file.
1244 mPendingInits.add(transportName);
1245 try {
1246 (new FileOutputStream(initPendingFile)).close();
1247 } catch (IOException ioe) {
1248 // Something is badly wrong with our permissions; just try to move on
1249 }
1250 } else {
1251 // No more initialization needed; wipe the journal and reset our state.
1252 initPendingFile.delete();
1253 mPendingInits.remove(transportName);
1254 }
1255 } catch (RemoteException e) {
1256 // can't happen; the transport is local
1257 }
1258 }
1259
Christopher Tated55e18a2009-09-21 10:12:59 -07001260 // Reset all of our bookkeeping, in response to having been told that
1261 // the backend data has been wiped [due to idle expiry, for example],
1262 // so we must re-upload all saved settings.
1263 void resetBackupState(File stateFileDir) {
1264 synchronized (mQueueLock) {
1265 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001266 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001267 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001268
Christopher Tate84725812010-02-04 15:52:40 -08001269 mCurrentToken = 0;
1270 writeRestoreTokens();
1271
Christopher Tated55e18a2009-09-21 10:12:59 -07001272 // Remove all the state files
1273 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001274 // ... but don't touch the needs-init sentinel
1275 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1276 sf.delete();
1277 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001278 }
Christopher Tate45597642011-04-04 16:59:21 -07001279 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001280
Christopher Tate45597642011-04-04 16:59:21 -07001281 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001282 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001283 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001284 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001285 HashSet<String> participants = mBackupParticipants.valueAt(i);
1286 if (participants != null) {
1287 for (String packageName : participants) {
1288 dataChangedImpl(packageName);
1289 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001290 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001291 }
1292 }
1293 }
1294
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001295 // Add a transport to our set of available backends. If 'transport' is null, this
1296 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001297 private void registerTransport(String name, IBackupTransport transport) {
1298 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001299 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001300 if (transport != null) {
1301 mTransports.put(name, transport);
1302 } else {
1303 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001304 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001305 mCurrentTransport = null;
1306 }
1307 // Nothing further to do in the unregistration case
1308 return;
1309 }
Christopher Tate91717492009-06-26 21:07:13 -07001310 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001311
1312 // If the init sentinel file exists, we need to be sure to perform the init
1313 // as soon as practical. We also create the state directory at registration
1314 // time to ensure it's present from the outset.
1315 try {
1316 String transportName = transport.transportDirName();
1317 File stateDir = new File(mBaseStateDir, transportName);
1318 stateDir.mkdirs();
1319
1320 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1321 if (initSentinel.exists()) {
1322 synchronized (mQueueLock) {
1323 mPendingInits.add(transportName);
1324
1325 // TODO: pick a better starting time than now + 1 minute
1326 long delay = 1000 * 60; // one minute, in milliseconds
1327 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1328 System.currentTimeMillis() + delay, mRunInitIntent);
1329 }
1330 }
1331 } catch (RemoteException e) {
1332 // can't happen, the transport is local
1333 }
Christopher Tate91717492009-06-26 21:07:13 -07001334 }
1335
Christopher Tate3799bc22009-05-06 16:13:56 -07001336 // ----- Track installation/removal of packages -----
1337 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1338 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001339 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001340
Christopher Tate3799bc22009-05-06 16:13:56 -07001341 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001342 boolean replacing = false;
1343 boolean added = false;
1344 Bundle extras = intent.getExtras();
1345 String pkgList[] = null;
1346 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001347 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001348 Uri uri = intent.getData();
1349 if (uri == null) {
1350 return;
1351 }
1352 String pkgName = uri.getSchemeSpecificPart();
1353 if (pkgName != null) {
1354 pkgList = new String[] { pkgName };
1355 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001356 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1357 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001358 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001359 added = true;
1360 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001361 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001362 added = false;
1363 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1364 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001365
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001366 if (pkgList == null || pkgList.length == 0) {
1367 return;
1368 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001369
1370 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001371 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001372 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001373 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001374 // This is the package-replaced case; we just remove the entry
1375 // under the old uid and fall through to re-add.
1376 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001377 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001378 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001379 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001380 } else {
1381 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001382 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1383 } else {
1384 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001385 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001386 }
1387 }
1388 }
1389 }
1390 };
1391
Dan Egnor87a02bc2009-06-17 02:30:10 -07001392 // ----- Track connection to GoogleBackupTransport service -----
1393 ServiceConnection mGoogleConnection = new ServiceConnection() {
1394 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001395 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001396 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001397 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001398 }
1399
1400 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001402 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001403 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001404 }
1405 };
1406
Christopher Tate0bacfd22012-01-11 14:41:19 -08001407 // Add the backup agents in the given packages to our set of known backup participants.
1408 // If 'packageNames' is null, adds all backup agents in the whole system.
1409 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001410 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001411 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001412 if (packageNames != null) {
1413 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1414 for (String packageName : packageNames) {
1415 addPackageParticipantsLockedInner(packageName, targetApps);
1416 }
1417 } else {
1418 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1419 addPackageParticipantsLockedInner(null, targetApps);
1420 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001421 }
1422
Christopher Tate181fafa2009-05-14 11:12:14 -07001423 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001424 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001425 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001426 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001427 }
1428
Dan Egnorefe52642009-06-24 00:16:33 -07001429 for (PackageInfo pkg : targetPkgs) {
1430 if (packageName == null || pkg.packageName.equals(packageName)) {
1431 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001432 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001433 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001434 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001435 mBackupParticipants.put(uid, set);
1436 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001437 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001438 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001439
Christopher Tatee82f68d2012-10-23 15:07:38 -07001440 // Schedule a backup for it on general principles
1441 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1442 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001443 }
Christopher Tate487529a2009-04-29 14:03:25 -07001444 }
1445 }
1446
Christopher Tate0bacfd22012-01-11 14:41:19 -08001447 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001448 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001449 if (packageNames == null) {
1450 Slog.w(TAG, "removePackageParticipants with null list");
1451 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001452 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001453
Christopher Tatea3d55342012-03-27 13:16:18 -07001454 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1455 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001456 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001457 // Known previous UID, so we know which package set to check
1458 HashSet<String> set = mBackupParticipants.get(oldUid);
1459 if (set != null && set.contains(pkg)) {
1460 removePackageFromSetLocked(set, pkg);
1461 if (set.isEmpty()) {
1462 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1463 mBackupParticipants.remove(oldUid);
1464 }
1465 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001466 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001467 }
1468
Christopher Tatea3d55342012-03-27 13:16:18 -07001469 private void removePackageFromSetLocked(final HashSet<String> set,
1470 final String packageName) {
1471 if (set.contains(packageName)) {
1472 // Found it. Remove this one package from the bookkeeping, and
1473 // if it's the last participating app under this uid we drop the
1474 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001475 // Note that we deliberately leave it 'known' in the "ever backed up"
1476 // bookkeeping so that its current-dataset data will be retrieved
1477 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001478 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001479 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001480 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001481 }
1482 }
1483
Christopher Tate181fafa2009-05-14 11:12:14 -07001484 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001485 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001486 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001487 int flags = PackageManager.GET_SIGNATURES;
1488 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1489 int N = packages.size();
1490 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001491 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001492 try {
1493 ApplicationInfo app = pkg.applicationInfo;
1494 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001495 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001496 packages.remove(a);
1497 }
1498 else {
1499 // we will need the shared library path, so look that up and store it here
1500 app = mPackageManager.getApplicationInfo(pkg.packageName,
1501 PackageManager.GET_SHARED_LIBRARY_FILES);
1502 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1503 }
1504 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001505 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001506 }
1507 }
Dan Egnorefe52642009-06-24 00:16:33 -07001508 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001509 }
Christopher Tateaa088442009-06-16 18:25:46 -07001510
Christopher Tate84725812010-02-04 15:52:40 -08001511 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001512 // backed up at least once
1513 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001514 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1515
1516 synchronized (mEverStoredApps) {
1517 if (!mEverStoredApps.add(packageName)) return;
1518
1519 RandomAccessFile out = null;
1520 try {
1521 out = new RandomAccessFile(mEverStored, "rws");
1522 out.seek(out.length());
1523 out.writeUTF(packageName);
1524 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001526 } finally {
1527 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001528 }
1529 }
1530 }
1531
Christopher Tatee97e8072009-07-15 16:45:50 -07001532 // Remove our awareness of having ever backed up the given package
1533 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001534 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1535 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001536
Dan Egnor852f8e42009-09-30 11:20:45 -07001537 synchronized (mEverStoredApps) {
1538 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1539 // we'll recognize on initialization time that the package no longer
1540 // exists and fix it up then.
1541 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1542 RandomAccessFile known = null;
1543 try {
1544 known = new RandomAccessFile(tempKnownFile, "rws");
1545 mEverStoredApps.remove(packageName);
1546 for (String s : mEverStoredApps) {
1547 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001548 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001549 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001550 known.close();
1551 known = null;
1552 if (!tempKnownFile.renameTo(mEverStored)) {
1553 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1554 }
1555 } catch (IOException e) {
1556 // Bad: we couldn't create the new copy. For safety's sake we
1557 // abandon the whole process and remove all what's-backed-up
1558 // state entirely, meaning we'll force a backup pass for every
1559 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001561 mEverStoredApps.clear();
1562 tempKnownFile.delete();
1563 mEverStored.delete();
1564 } finally {
1565 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001566 }
1567 }
1568 }
1569
Christopher Tateb49ceb32010-02-08 16:22:24 -08001570 // Persistently record the current and ancestral backup tokens as well
1571 // as the set of packages with data [supposedly] available in the
1572 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001573 void writeRestoreTokens() {
1574 try {
1575 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001576
1577 // First, the version number of this record, for futureproofing
1578 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1579
1580 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001581 af.writeLong(mAncestralToken);
1582 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001583
1584 // Now write the set of ancestral packages
1585 if (mAncestralPackages == null) {
1586 af.writeInt(-1);
1587 } else {
1588 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001590 for (String pkgName : mAncestralPackages) {
1591 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001592 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001593 }
1594 }
Christopher Tate84725812010-02-04 15:52:40 -08001595 af.close();
1596 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001597 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001598 }
1599 }
1600
Dan Egnor87a02bc2009-06-17 02:30:10 -07001601 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001602 private IBackupTransport getTransport(String transportName) {
1603 synchronized (mTransports) {
1604 IBackupTransport transport = mTransports.get(transportName);
1605 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001606 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001607 }
1608 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001609 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001610 }
1611
Christopher Tatedf01dea2009-06-09 20:45:02 -07001612 // fire off a backup agent, blocking until it attaches or times out
1613 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1614 IBackupAgent agent = null;
1615 synchronized(mAgentConnectLock) {
1616 mConnecting = true;
1617 mConnectedAgent = null;
1618 try {
1619 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001621
1622 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001623 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001624 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1625 while (mConnecting && mConnectedAgent == null
1626 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001627 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001628 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001629 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001630 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001631 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001632 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001633 return null;
1634 }
1635 }
1636
1637 // if we timed out with no connect, abort and move on
1638 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001639 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001640 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001641 return null;
1642 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001643 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001644 agent = mConnectedAgent;
1645 }
1646 } catch (RemoteException e) {
1647 // can't happen
1648 }
1649 }
1650 return agent;
1651 }
1652
Christopher Tatec7b31e32009-06-10 15:49:30 -07001653 // clear an application's data, blocking until the operation completes or times out
1654 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001655 // Don't wipe packages marked allowClearUserData=false
1656 try {
1657 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1658 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001659 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001660 + packageName);
1661 return;
1662 }
1663 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001664 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001665 return;
1666 }
1667
Christopher Tatec7b31e32009-06-10 15:49:30 -07001668 ClearDataObserver observer = new ClearDataObserver();
1669
1670 synchronized(mClearDataLock) {
1671 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001672 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001673 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001674 } catch (RemoteException e) {
1675 // can't happen because the activity manager is in this process
1676 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001677
1678 // only wait 10 seconds for the clear data to happen
1679 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1680 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1681 try {
1682 mClearDataLock.wait(5000);
1683 } catch (InterruptedException e) {
1684 // won't happen, but still.
1685 mClearingData = false;
1686 }
1687 }
1688 }
1689 }
1690
1691 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001692 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001693 synchronized(mClearDataLock) {
1694 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001695 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001696 }
1697 }
1698 }
1699
Christopher Tate1bb69062010-02-19 17:02:12 -08001700 // Get the restore-set token for the best-available restore set for this package:
1701 // the active set if possible, else the ancestral one. Returns zero if none available.
1702 long getAvailableRestoreToken(String packageName) {
1703 long token = mAncestralToken;
1704 synchronized (mQueueLock) {
1705 if (mEverStoredApps.contains(packageName)) {
1706 token = mCurrentToken;
1707 }
1708 }
1709 return token;
1710 }
1711
Christopher Tate44a27902010-01-27 17:15:49 -08001712 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001713 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1714
1715 interface BackupRestoreTask {
1716 // Execute one tick of whatever state machine the task implements
1717 void execute();
1718
1719 // An operation that wanted a callback has completed
1720 void operationComplete();
1721
1722 // An operation that wanted a callback has timed out
1723 void handleTimeout();
1724 }
1725
1726 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1727 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1728 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001729 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001730 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1731
1732 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1733 mBackupHandler.sendMessageDelayed(msg, interval);
1734 }
1735 }
1736
1737 // synchronous waiter case
1738 boolean waitUntilOperationComplete(int token) {
1739 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1740 + Integer.toHexString(token));
1741 int finalState = OP_PENDING;
1742 Operation op = null;
1743 synchronized (mCurrentOpLock) {
1744 while (true) {
1745 op = mCurrentOperations.get(token);
1746 if (op == null) {
1747 // mysterious disappearance: treat as success with no callback
1748 break;
1749 } else {
1750 if (op.state == OP_PENDING) {
1751 try {
1752 mCurrentOpLock.wait();
1753 } catch (InterruptedException e) {}
1754 // When the wait is notified we loop around and recheck the current state
1755 } else {
1756 // No longer pending; we're done
1757 finalState = op.state;
1758 break;
1759 }
Christopher Tate44a27902010-01-27 17:15:49 -08001760 }
Christopher Tate44a27902010-01-27 17:15:49 -08001761 }
1762 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001763
Christopher Tate44a27902010-01-27 17:15:49 -08001764 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001765 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001766 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001767 return finalState == OP_ACKNOWLEDGED;
1768 }
1769
Christopher Tate8e294d42011-08-31 20:37:12 -07001770 void handleTimeout(int token, Object obj) {
1771 // Notify any synchronous waiters
1772 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001773 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001774 op = mCurrentOperations.get(token);
1775 if (MORE_DEBUG) {
1776 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1777 + " but no op found");
1778 }
1779 int state = (op != null) ? op.state : OP_TIMEOUT;
1780 if (state == OP_PENDING) {
1781 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1782 op.state = OP_TIMEOUT;
1783 mCurrentOperations.put(token, op);
1784 }
1785 mCurrentOpLock.notifyAll();
1786 }
1787
1788 // If there's a TimeoutHandler for this event, call it
1789 if (op != null && op.callback != null) {
1790 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001791 }
Christopher Tate44a27902010-01-27 17:15:49 -08001792 }
1793
Christopher Tate043dadc2009-06-02 16:11:00 -07001794 // ----- Back up a set of applications via a worker thread -----
1795
Christopher Tate8e294d42011-08-31 20:37:12 -07001796 enum BackupState {
1797 INITIAL,
1798 RUNNING_QUEUE,
1799 FINAL
1800 }
1801
1802 class PerformBackupTask implements BackupRestoreTask {
1803 private static final String TAG = "PerformBackupTask";
1804
Christopher Tateaa088442009-06-16 18:25:46 -07001805 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001806 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001807 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001808 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001809 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001810 BackupState mCurrentState;
1811
1812 // carried information about the current in-flight operation
1813 PackageInfo mCurrentPackage;
1814 File mSavedStateName;
1815 File mBackupDataName;
1816 File mNewStateName;
1817 ParcelFileDescriptor mSavedState;
1818 ParcelFileDescriptor mBackupData;
1819 ParcelFileDescriptor mNewState;
1820 int mStatus;
1821 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001822
Christopher Tate44a27902010-01-27 17:15:49 -08001823 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001824 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001825 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001826 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001827 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001828
1829 try {
1830 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1831 } catch (RemoteException e) {
1832 // can't happen; the transport is local
1833 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001834
1835 mCurrentState = BackupState.INITIAL;
1836 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001837
1838 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001839 }
1840
Christopher Tate8e294d42011-08-31 20:37:12 -07001841 // Main entry point: perform one chunk of work, updating the state as appropriate
1842 // and reposting the next chunk to the primary backup handler thread.
1843 @Override
1844 public void execute() {
1845 switch (mCurrentState) {
1846 case INITIAL:
1847 beginBackup();
1848 break;
1849
1850 case RUNNING_QUEUE:
1851 invokeNextAgent();
1852 break;
1853
1854 case FINAL:
1855 if (!mFinished) finalizeBackup();
1856 else {
1857 Slog.e(TAG, "Duplicate finish");
1858 }
Christopher Tate2982d062011-09-06 20:35:24 -07001859 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001860 break;
1861 }
1862 }
1863
1864 // We're starting a backup pass. Initialize the transport and send
1865 // the PM metadata blob if we haven't already.
1866 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001867 if (DEBUG_BACKUP_TRACE) {
1868 clearBackupTrace();
1869 StringBuilder b = new StringBuilder(256);
1870 b.append("beginBackup: [");
1871 for (BackupRequest req : mOriginalQueue) {
1872 b.append(' ');
1873 b.append(req.packageName);
1874 }
1875 b.append(" ]");
1876 addBackupTrace(b.toString());
1877 }
1878
Christopher Tate8e294d42011-08-31 20:37:12 -07001879 mStatus = BackupConstants.TRANSPORT_OK;
1880
1881 // Sanity check: if the queue is empty we have no work to do.
1882 if (mOriginalQueue.isEmpty()) {
1883 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001884 addBackupTrace("queue empty at begin");
1885 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001886 return;
1887 }
1888
1889 // We need to retain the original queue contents in case of transport
1890 // failure, but we want a working copy that we can manipulate along
1891 // the way.
1892 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1893
Joe Onorato8a9b2202010-02-26 18:56:32 -08001894 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001895
Christopher Tate8e294d42011-08-31 20:37:12 -07001896 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001897 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001898 final String transportName = mTransport.transportDirName();
1899 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001900
Dan Egnor852f8e42009-09-30 11:20:45 -07001901 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001902 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001903 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001904 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001905 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001906 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001907
1908 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001909 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001910 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001911 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001912 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001913 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001914 }
Dan Egnor01445162009-09-21 17:04:05 -07001915 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001916
1917 // The package manager doesn't have a proper <application> etc, but since
1918 // it's running here in the system process we can just set up its agent
1919 // directly and use a synthetic BackupRequest. We always run this pass
1920 // because it's cheap and this way we guarantee that we don't get out of
1921 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001922 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001923 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1924 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001925 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001926 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001927 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001928 }
Christopher Tate90967f42009-09-20 15:28:33 -07001929
Christopher Tate8e294d42011-08-31 20:37:12 -07001930 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1931 // The backend reports that our dataset has been wiped. Note this in
1932 // the event log; the no-success code below will reset the backup
1933 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001934 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001935 }
1936 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001937 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001938 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001939 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001940 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001941 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1942 // metadata and its completion/timeout callback will continue the state
1943 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001944 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001945 if (mStatus != BackupConstants.TRANSPORT_OK) {
1946 // if things went wrong at this point, we need to
1947 // restage everything and try again later.
1948 resetBackupState(mStateDir); // Just to make sure.
1949 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001950 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001951 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001952 }
1953
Christopher Tate8e294d42011-08-31 20:37:12 -07001954 // Transport has been initialized and the PM metadata submitted successfully
1955 // if that was warranted. Now we process the single next thing in the queue.
1956 void invokeNextAgent() {
1957 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001958 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001959
Christopher Tate8e294d42011-08-31 20:37:12 -07001960 // Sanity check that we have work to do. If not, skip to the end where
1961 // we reestablish the wakelock invariants etc.
1962 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001963 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001964 executeNextState(BackupState.FINAL);
1965 return;
1966 }
1967
1968 // pop the entry we're going to process on this step
1969 BackupRequest request = mQueue.get(0);
1970 mQueue.remove(0);
1971
1972 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001973 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001974
1975 // Verify that the requested app exists; it might be something that
1976 // requested a backup but was then uninstalled. The request was
1977 // journalled and rather than tamper with the journal it's safer
1978 // to sanity-check here. This also gives us the classname of the
1979 // package's backup agent.
1980 try {
1981 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1982 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001983 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1984 // The manifest has changed but we had a stale backup request pending.
1985 // This won't happen again because the app won't be requesting further
1986 // backups.
1987 Slog.i(TAG, "Package " + request.packageName
1988 + " no longer supports backup; skipping");
1989 addBackupTrace("skipping - no agent, completion is noop");
1990 executeNextState(BackupState.RUNNING_QUEUE);
1991 return;
1992 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001993
Christopher Tate043dadc2009-06-02 16:11:00 -07001994 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001995 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001996 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1997 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001998 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001999 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07002000 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002001 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2002 // at this point we'll either get a completion callback from the
2003 // agent, or a timeout message on the main handler. either way, we're
2004 // done here as long as we're successful so far.
2005 } else {
2006 // Timeout waiting for the agent
2007 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002008 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002009 } catch (SecurityException ex) {
2010 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002011 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002012 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002013 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002014 }
2015 } catch (NameNotFoundException e) {
2016 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002017 addBackupTrace("no such package");
2018 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002019 } finally {
2020 mWakelock.setWorkSource(null);
2021
2022 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002023 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002024 if (mStatus != BackupConstants.TRANSPORT_OK) {
2025 BackupState nextState = BackupState.RUNNING_QUEUE;
2026
2027 // An agent-level failure means we reenqueue this one agent for
2028 // a later retry, but otherwise proceed normally.
2029 if (mStatus == BackupConstants.AGENT_ERROR) {
2030 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2031 + " - restaging");
2032 dataChangedImpl(request.packageName);
2033 mStatus = BackupConstants.TRANSPORT_OK;
2034 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002035 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2036 // Failed lookup of the app, so we couldn't bring up an agent, but
2037 // we're otherwise fine. Just drop it and go on to the next as usual.
2038 mStatus = BackupConstants.TRANSPORT_OK;
2039 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002040 // Transport-level failure means we reenqueue everything
2041 revertAndEndBackup();
2042 nextState = BackupState.FINAL;
2043 }
2044
2045 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002046 } else {
2047 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002048 }
2049 }
2050 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002051
Christopher Tate8e294d42011-08-31 20:37:12 -07002052 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002053 addBackupTrace("finishing");
2054
Christopher Tate8e294d42011-08-31 20:37:12 -07002055 // Either backup was successful, in which case we of course do not need
2056 // this pass's journal any more; or it failed, in which case we just
2057 // re-enqueued all of these packages in the current active journal.
2058 // Either way, we no longer need this pass's journal.
2059 if (mJournal != null && !mJournal.delete()) {
2060 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2061 }
2062
2063 // If everything actually went through and this is the first time we've
2064 // done a backup, we can now record what the current backup dataset token
2065 // is.
2066 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002067 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002068 try {
2069 mCurrentToken = mTransport.getCurrentRestoreSet();
2070 } catch (RemoteException e) {} // can't happen
2071 writeRestoreTokens();
2072 }
2073
Christopher Tate336a6492011-10-05 16:05:43 -07002074 // Set up the next backup pass - at this point we can set mBackupRunning
2075 // to false to allow another pass to fire, because we're done with the
2076 // state machine sequence and the wakelock is refcounted.
2077 synchronized (mQueueLock) {
2078 mBackupRunning = false;
2079 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002080 // Make sure we back up everything and perform the one-time init
2081 clearMetadata();
2082 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002083 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002084 backupNow();
2085 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002086 }
2087
2088 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002089 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002090 Slog.i(TAG, "Backup pass finished.");
2091 mWakelock.release();
2092 }
2093
Christopher Tatee659fb92011-10-10 16:34:50 -07002094 // Remove the PM metadata state. This will generate an init on the next pass.
2095 void clearMetadata() {
2096 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2097 if (pmState.exists()) pmState.delete();
2098 }
2099
Christopher Tate8e294d42011-08-31 20:37:12 -07002100 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2101 // handler in case it doesn't get back to us.
2102 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002103 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002104 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2105 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002106
Christopher Tate8e294d42011-08-31 20:37:12 -07002107 mSavedStateName = new File(mStateDir, packageName);
2108 mBackupDataName = new File(mDataDir, packageName + ".data");
2109 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002110
Christopher Tate8e294d42011-08-31 20:37:12 -07002111 mSavedState = null;
2112 mBackupData = null;
2113 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002114
Christopher Tate4a627c72011-04-01 14:43:32 -07002115 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002116 try {
2117 // Look up the package info & signatures. This is first so that if it
2118 // throws an exception, there's no file setup yet that would need to
2119 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002120 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002121 // The metadata 'package' is synthetic; construct one and make
2122 // sure our global state is pointed at it
2123 mCurrentPackage = new PackageInfo();
2124 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002125 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002126
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002128 // the saved-state "file". This is by definition an incremental,
2129 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002130 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002131 ParcelFileDescriptor.MODE_READ_ONLY |
2132 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002133
Christopher Tate8e294d42011-08-31 20:37:12 -07002134 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002135 ParcelFileDescriptor.MODE_READ_WRITE |
2136 ParcelFileDescriptor.MODE_CREATE |
2137 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002138
Christopher Tate8e294d42011-08-31 20:37:12 -07002139 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002140 ParcelFileDescriptor.MODE_READ_WRITE |
2141 ParcelFileDescriptor.MODE_CREATE |
2142 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002143
Christopher Tate44a27902010-01-27 17:15:49 -08002144 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002145 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002146 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002147 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002148 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002149 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002150 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002151 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002152 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2153 e.toString());
2154 agentErrorCleanup();
2155 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002156 }
2157
Christopher Tate8e294d42011-08-31 20:37:12 -07002158 // At this point the agent is off and running. The next thing to happen will
2159 // either be a callback from the agent, at which point we'll process its data
2160 // for transport, or a timeout. Either way the next phase will happen in
2161 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002162 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002163 return BackupConstants.TRANSPORT_OK;
2164 }
2165
2166 @Override
2167 public void operationComplete() {
2168 // Okay, the agent successfully reported back to us. Spin the data off to the
2169 // transport and proceed with the next stage.
2170 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2171 + mCurrentPackage.packageName);
2172 mBackupHandler.removeMessages(MSG_TIMEOUT);
2173 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002174 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002175
2176 ParcelFileDescriptor backupData = null;
2177 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002178 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002179 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002180 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002181 if (mStatus == BackupConstants.TRANSPORT_OK) {
2182 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002183 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002184 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002185 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002186 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002187
Dan Egnor83861e72009-09-17 16:17:55 -07002188 // TODO - We call finishBackup() for each application backed up, because
2189 // we need to know now whether it succeeded or failed. Instead, we should
2190 // hold off on finishBackup() until the end, which implies holding off on
2191 // renaming *all* the output state files (see below) until that happens.
2192
Christopher Tate6de74ff2012-01-17 15:20:32 -08002193 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002194 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002195 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002196 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002197 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002198 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002199 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002200 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002201 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002202 }
2203
2204 // After successful transport, delete the now-stale data
2205 // and juggle the files so that next time we supply the agent
2206 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002207 if (mStatus == BackupConstants.TRANSPORT_OK) {
2208 mBackupDataName.delete();
2209 mNewStateName.renameTo(mSavedStateName);
2210 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2211 mCurrentPackage.packageName, size);
2212 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002213 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002214 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2215 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002216 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002217 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002218 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2219 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2220 mCurrentPackage.packageName);
2221 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002222 } finally {
2223 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002224 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002225
Christopher Tate8e294d42011-08-31 20:37:12 -07002226 // If we encountered an error here it's a transport-level failure. That
2227 // means we need to halt everything and reschedule everything for next time.
2228 final BackupState nextState;
2229 if (mStatus != BackupConstants.TRANSPORT_OK) {
2230 revertAndEndBackup();
2231 nextState = BackupState.FINAL;
2232 } else {
2233 // Success! Proceed with the next app if any, otherwise we're done.
2234 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2235 }
2236
2237 executeNextState(nextState);
2238 }
2239
2240 @Override
2241 public void handleTimeout() {
2242 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2243 // it for the next time we run a backup pass.
2244 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2245 // fail repeatedly (i.e. have proved themselves to be buggy).
2246 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2247 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2248 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002249 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002250 agentErrorCleanup();
2251 dataChangedImpl(mCurrentPackage.packageName);
2252 }
2253
2254 void revertAndEndBackup() {
2255 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002256 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002257 for (BackupRequest request : mOriginalQueue) {
2258 dataChangedImpl(request.packageName);
2259 }
2260 // We also want to reset the backup schedule based on whatever
2261 // the transport suggests by way of retry/backoff time.
2262 restartBackupAlarm();
2263 }
2264
2265 void agentErrorCleanup() {
2266 mBackupDataName.delete();
2267 mNewStateName.delete();
2268 clearAgentState();
2269
2270 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2271 }
2272
2273 // Cleanup common to both success and failure cases
2274 void clearAgentState() {
2275 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2276 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2277 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2278 mSavedState = mBackupData = mNewState = null;
2279 synchronized (mCurrentOpLock) {
2280 mCurrentOperations.clear();
2281 }
2282
2283 // If this was a pseudopackage there's no associated Activity Manager state
2284 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002285 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002286 try { // unbind even on timeout, just in case
2287 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2288 } catch (RemoteException e) {}
2289 }
2290 }
2291
2292 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002293 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002294 synchronized (mQueueLock) {
2295 try {
2296 startBackupAlarmsLocked(mTransport.requestBackupTime());
2297 } catch (RemoteException e) { /* cannot happen */ }
2298 }
2299 }
2300
2301 void executeNextState(BackupState nextState) {
2302 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2303 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002304 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002305 mCurrentState = nextState;
2306 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2307 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002308 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002309 }
2310
Christopher Tatedf01dea2009-06-09 20:45:02 -07002311
Christopher Tate294b5122013-02-19 14:08:59 -08002312 // ----- Full backup/restore to a file/socket -----
Christopher Tate4a627c72011-04-01 14:43:32 -07002313
Christopher Tate294b5122013-02-19 14:08:59 -08002314 abstract class ObbServiceClient {
2315 public IObbBackupService mObbService;
2316 public void setObbBinder(IObbBackupService binder) {
2317 mObbService = binder;
2318 }
2319 }
2320
2321 class FullBackupObbConnection implements ServiceConnection {
2322 volatile IObbBackupService mService;
2323
2324 FullBackupObbConnection() {
2325 mService = null;
2326 }
2327
2328 public void establish() {
2329 if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2330 Intent obbIntent = new Intent().setComponent(new ComponentName(
2331 "com.android.sharedstoragebackup",
2332 "com.android.sharedstoragebackup.ObbBackupService"));
2333 BackupManagerService.this.mContext.bindService(
2334 obbIntent, this, Context.BIND_AUTO_CREATE);
2335 }
2336
2337 public void tearDown() {
2338 BackupManagerService.this.mContext.unbindService(this);
2339 }
2340
2341 public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2342 boolean success = false;
2343 waitForConnection();
2344
2345 ParcelFileDescriptor[] pipes = null;
2346 try {
2347 pipes = ParcelFileDescriptor.createPipe();
2348 int token = generateToken();
2349 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2350 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2351 routeSocketDataToOutput(pipes[0], out);
2352 success = waitUntilOperationComplete(token);
2353 } catch (Exception e) {
2354 Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2355 } finally {
2356 try {
2357 out.flush();
2358 if (pipes != null) {
2359 if (pipes[0] != null) pipes[0].close();
2360 if (pipes[1] != null) pipes[1].close();
2361 }
2362 } catch (IOException e) {
2363 Slog.w(TAG, "I/O error closing down OBB backup", e);
2364 }
2365 }
2366 return success;
2367 }
2368
2369 public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2370 long fileSize, int type, String path, long mode, long mtime,
2371 int token, IBackupManager callbackBinder) {
2372 waitForConnection();
2373
2374 try {
2375 mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2376 token, callbackBinder);
2377 } catch (Exception e) {
2378 Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2379 }
2380 }
2381
2382 private void waitForConnection() {
2383 synchronized (this) {
2384 while (mService == null) {
2385 if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2386 try {
2387 this.wait();
2388 } catch (InterruptedException e) { /* never interrupted */ }
2389 }
2390 if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2391 }
2392 }
2393
2394 @Override
2395 public void onServiceConnected(ComponentName name, IBinder service) {
2396 synchronized (this) {
2397 mService = IObbBackupService.Stub.asInterface(service);
2398 if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2399 + " connected on " + this);
2400 this.notifyAll();
2401 }
2402 }
2403
2404 @Override
2405 public void onServiceDisconnected(ComponentName name) {
2406 synchronized (this) {
2407 mService = null;
2408 if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2409 this.notifyAll();
2410 }
2411 }
2412
2413 }
2414
2415 private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2416 throws IOException {
2417 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2418 DataInputStream in = new DataInputStream(raw);
2419
2420 byte[] buffer = new byte[32 * 1024];
2421 int chunkTotal;
2422 while ((chunkTotal = in.readInt()) > 0) {
2423 while (chunkTotal > 0) {
2424 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2425 int nRead = in.read(buffer, 0, toRead);
2426 out.write(buffer, 0, nRead);
2427 chunkTotal -= nRead;
2428 }
2429 }
2430 }
2431
2432 class PerformFullBackupTask extends ObbServiceClient implements Runnable {
Christopher Tate4a627c72011-04-01 14:43:32 -07002433 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002434 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002435 IFullBackupRestoreObserver mObserver;
2436 boolean mIncludeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002437 boolean mIncludeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002438 boolean mIncludeShared;
2439 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002440 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002441 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002442 String mCurrentPassword;
2443 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002444 AtomicBoolean mLatchObject;
2445 File mFilesDir;
2446 File mManifestFile;
Christopher Tate294b5122013-02-19 14:08:59 -08002447
Christopher Tate4a627c72011-04-01 14:43:32 -07002448
Christopher Tate7926a692011-07-11 11:31:57 -07002449 class FullBackupRunner implements Runnable {
2450 PackageInfo mPackage;
2451 IBackupAgent mAgent;
2452 ParcelFileDescriptor mPipe;
2453 int mToken;
2454 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002455 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002456
2457 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002458 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002459 mPackage = pack;
2460 mAgent = agent;
2461 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2462 mToken = token;
2463 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002464 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002465 }
2466
2467 @Override
2468 public void run() {
2469 try {
2470 BackupDataOutput output = new BackupDataOutput(
2471 mPipe.getFileDescriptor());
2472
Christopher Tate73d73692012-01-20 17:11:31 -08002473 if (mWriteManifest) {
2474 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2475 writeAppManifest(mPackage, mManifestFile, mSendApk);
2476 FullBackup.backupToTar(mPackage.packageName, null, null,
2477 mFilesDir.getAbsolutePath(),
2478 mManifestFile.getAbsolutePath(),
2479 output);
2480 }
Christopher Tate7926a692011-07-11 11:31:57 -07002481
2482 if (mSendApk) {
2483 writeApkToBackup(mPackage, output);
2484 }
2485
Christopher Tatec58efa62011-08-01 19:20:14 -07002486 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002487 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002488 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2489 } catch (IOException e) {
2490 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2491 } catch (RemoteException e) {
2492 Slog.e(TAG, "Remote agent vanished during full backup of "
2493 + mPackage.packageName);
2494 } finally {
2495 try {
2496 mPipe.close();
2497 } catch (IOException e) {}
2498 }
2499 }
2500 }
2501
Christopher Tate4a627c72011-04-01 14:43:32 -07002502 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate294b5122013-02-19 14:08:59 -08002503 boolean includeApks, boolean includeObbs, boolean includeShared,
2504 String curPassword, String encryptPassword, boolean doAllApps,
2505 boolean doSystem, String[] packages, AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002506 mOutputFile = fd;
2507 mObserver = observer;
2508 mIncludeApks = includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002509 mIncludeObbs = includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002510 mIncludeShared = includeShared;
2511 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002512 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002513 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002514 mCurrentPassword = curPassword;
2515 // when backing up, if there is a current backup password, we require that
2516 // the user use a nonempty encryption password as well. if one is supplied
2517 // in the UI we use that, but if the UI was left empty we fall back to the
2518 // current backup password (which was supplied by the user as well).
2519 if (encryptPassword == null || "".equals(encryptPassword)) {
2520 mEncryptPassword = curPassword;
2521 } else {
2522 mEncryptPassword = encryptPassword;
2523 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002524 mLatchObject = latch;
2525
2526 mFilesDir = new File("/data/system");
2527 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2528 }
2529
2530 @Override
2531 public void run() {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002532 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate294b5122013-02-19 14:08:59 -08002533
2534 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
2535 FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2536 obbConnection.establish(); // we'll want this later
2537
Christopher Tate4a627c72011-04-01 14:43:32 -07002538 sendStartBackup();
2539
2540 // doAllApps supersedes the package set if any
2541 if (mAllApps) {
2542 packagesToBackup = mPackageManager.getInstalledPackages(
2543 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002544 // Exclude system apps if we've been asked to do so
2545 if (mIncludeSystem == false) {
2546 for (int i = 0; i < packagesToBackup.size(); ) {
2547 PackageInfo pkg = packagesToBackup.get(i);
2548 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2549 packagesToBackup.remove(i);
2550 } else {
2551 i++;
2552 }
2553 }
2554 }
2555 }
2556
2557 // Now process the command line argument packages, if any. Note that explicitly-
2558 // named system-partition packages will be included even if includeSystem was
2559 // set to false.
2560 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002561 for (String pkgName : mPackages) {
2562 try {
2563 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2564 PackageManager.GET_SIGNATURES));
2565 } catch (NameNotFoundException e) {
2566 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2567 }
2568 }
2569 }
2570
Christopher Tate73d73692012-01-20 17:11:31 -08002571 // Cull any packages that have indicated that backups are not permitted, as well
2572 // as any explicit mention of the 'special' shared-storage agent package (we
2573 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002574 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002575 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002576 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2577 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002578 packagesToBackup.remove(i);
2579 } else {
2580 i++;
2581 }
2582 }
2583
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002584 // Cull any packages that run as system-domain uids but do not define their
2585 // own backup agents
2586 for (int i = 0; i < packagesToBackup.size(); ) {
2587 PackageInfo pkg = packagesToBackup.get(i);
2588 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2589 && (pkg.applicationInfo.backupAgentName == null)) {
2590 if (MORE_DEBUG) {
2591 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2592 }
2593 packagesToBackup.remove(i);
2594 } else {
2595 i++;
2596 }
2597 }
2598
Christopher Tate7926a692011-07-11 11:31:57 -07002599 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002600 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002601
Christopher Tate4a627c72011-04-01 14:43:32 -07002602 PackageInfo pkg = null;
2603 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002604 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002605 boolean compressing = COMPRESS_FULL_BACKUPS;
2606 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002607
Christopher Tateeef4ae42011-08-05 13:15:53 -07002608 // Verify that the given password matches the currently-active
2609 // backup password, if any
2610 if (hasBackupPassword()) {
2611 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2612 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2613 return;
2614 }
2615 }
2616
Christopher Tate7bdb0962011-07-13 19:30:21 -07002617 // Write the global file header. All strings are UTF-8 encoded; lines end
2618 // with a '\n' byte. Actual backup data begins immediately following the
2619 // final '\n'.
2620 //
2621 // line 1: "ANDROID BACKUP"
2622 // line 2: backup file format version, currently "1"
2623 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002624 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2625 //
2626 // When line 4 is not "none", then additional header data follows:
2627 //
2628 // line 5: user password salt [hex]
2629 // line 6: master key checksum salt [hex]
2630 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2631 // line 8: IV of the user key [hex]
2632 // line 9: master key blob [hex]
2633 // IV of the master key, master key itself, master key checksum hash
2634 //
2635 // The master key checksum is the master key plus its checksum salt, run through
2636 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2637 // correct password for decrypting the archive: the master key decrypted from
2638 // the archive using the user-supplied password is also run through PBKDF2 in
2639 // this way, and if the result does not match the checksum as stored in the
2640 // archive, then we know that the user-supplied password does not match the
2641 // archive's.
2642 StringBuilder headerbuf = new StringBuilder(1024);
2643
Christopher Tate7bdb0962011-07-13 19:30:21 -07002644 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002645 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2646 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002647
2648 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002649 // Set up the encryption stage if appropriate, and emit the correct header
2650 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002651 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2652 } else {
2653 headerbuf.append("none\n");
2654 }
2655
Christopher Tate7bdb0962011-07-13 19:30:21 -07002656 byte[] header = headerbuf.toString().getBytes("UTF-8");
2657 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002658
2659 // Set up the compression stage feeding into the encryption stage (if any)
2660 if (compressing) {
2661 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2662 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2663 }
2664
2665 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002666 } catch (Exception e) {
2667 // Should never happen!
2668 Slog.e(TAG, "Unable to emit archive header", e);
2669 return;
2670 }
2671
Christopher Tate73d73692012-01-20 17:11:31 -08002672 // Shared storage if requested
2673 if (mIncludeShared) {
2674 try {
2675 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2676 packagesToBackup.add(pkg);
2677 } catch (NameNotFoundException e) {
2678 Slog.e(TAG, "Unable to find shared-storage backup handler");
2679 }
2680 }
2681
Christopher Tateb0628bf2011-06-02 15:08:13 -07002682 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002683 int N = packagesToBackup.size();
2684 for (int i = 0; i < N; i++) {
2685 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002686 backupOnePackage(pkg, out);
Christopher Tate294b5122013-02-19 14:08:59 -08002687
2688 // after the app's agent runs to handle its private filesystem
2689 // contents, back up any OBB content it has on its behalf.
2690 if (mIncludeObbs) {
2691 boolean obbOkay = obbConnection.backupObbs(pkg, out);
2692 if (!obbOkay) {
2693 throw new RuntimeException("Failure writing OBB stack for " + pkg);
2694 }
2695 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002696 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002697
Christopher Tate6853fcf2011-08-10 17:52:21 -07002698 // Done!
2699 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002700 } catch (RemoteException e) {
2701 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002702 } catch (Exception e) {
2703 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002704 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002705 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002706 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002707 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002708 mOutputFile.close();
2709 } catch (IOException e) {
2710 /* nothing we can do about this */
2711 }
2712 synchronized (mCurrentOpLock) {
2713 mCurrentOperations.clear();
2714 }
2715 synchronized (mLatchObject) {
2716 mLatchObject.set(true);
2717 mLatchObject.notifyAll();
2718 }
2719 sendEndBackup();
Christopher Tate294b5122013-02-19 14:08:59 -08002720 obbConnection.tearDown();
Christopher Tate4a627c72011-04-01 14:43:32 -07002721 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002722 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002723 }
2724 }
2725
Christopher Tate2efd2db2011-07-19 16:32:49 -07002726 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2727 OutputStream ofstream) throws Exception {
2728 // User key will be used to encrypt the master key.
2729 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002730 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002731 PBKDF2_HASH_ROUNDS);
2732
2733 // the master key is random for each backup
2734 byte[] masterPw = new byte[256 / 8];
2735 mRng.nextBytes(masterPw);
2736 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2737
2738 // primary encryption of the datastream with the random key
2739 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2740 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2741 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2742 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2743
2744 // line 4: name of encryption algorithm
2745 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2746 headerbuf.append('\n');
2747 // line 5: user password salt [hex]
2748 headerbuf.append(byteArrayToHex(newUserSalt));
2749 headerbuf.append('\n');
2750 // line 6: master key checksum salt [hex]
2751 headerbuf.append(byteArrayToHex(checksumSalt));
2752 headerbuf.append('\n');
2753 // line 7: number of PBKDF2 rounds used [decimal]
2754 headerbuf.append(PBKDF2_HASH_ROUNDS);
2755 headerbuf.append('\n');
2756
2757 // line 8: IV of the user key [hex]
2758 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2759 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2760
2761 byte[] IV = mkC.getIV();
2762 headerbuf.append(byteArrayToHex(IV));
2763 headerbuf.append('\n');
2764
2765 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2766 // [byte] IV length = Niv
2767 // [array of Niv bytes] IV itself
2768 // [byte] master key length = Nmk
2769 // [array of Nmk bytes] master key itself
2770 // [byte] MK checksum hash length = Nck
2771 // [array of Nck bytes] master key checksum hash
2772 //
2773 // The checksum is the (master key + checksum salt), run through the
2774 // stated number of PBKDF2 rounds
2775 IV = c.getIV();
2776 byte[] mk = masterKeySpec.getEncoded();
2777 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2778 checksumSalt, PBKDF2_HASH_ROUNDS);
2779
2780 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2781 + checksum.length + 3);
2782 DataOutputStream mkOut = new DataOutputStream(blob);
2783 mkOut.writeByte(IV.length);
2784 mkOut.write(IV);
2785 mkOut.writeByte(mk.length);
2786 mkOut.write(mk);
2787 mkOut.writeByte(checksum.length);
2788 mkOut.write(checksum);
2789 mkOut.flush();
2790 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2791 headerbuf.append(byteArrayToHex(encryptedMk));
2792 headerbuf.append('\n');
2793
2794 return finalOutput;
2795 }
2796
2797 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002798 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002799 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2800
2801 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2802 IApplicationThread.BACKUP_MODE_FULL);
2803 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002804 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002805 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002806 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002807
Christopher Tateb0628bf2011-06-02 15:08:13 -07002808 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002809 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002810 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002811 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002812 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2813 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2814 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2815
Christopher Tate73d73692012-01-20 17:11:31 -08002816 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002817
Christopher Tate7926a692011-07-11 11:31:57 -07002818 final int token = generateToken();
2819 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002820 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002821 pipes[1].close(); // the runner has dup'd it
2822 pipes[1] = null;
2823 Thread t = new Thread(runner);
2824 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002825
Christopher Tate7926a692011-07-11 11:31:57 -07002826 // Now pull data from the app and stuff it into the compressor
2827 try {
Christopher Tate294b5122013-02-19 14:08:59 -08002828 routeSocketDataToOutput(pipes[0], out);
Christopher Tate7926a692011-07-11 11:31:57 -07002829 } catch (IOException e) {
2830 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002831 }
2832
Christopher Tateb0628bf2011-06-02 15:08:13 -07002833 if (!waitUntilOperationComplete(token)) {
2834 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2835 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002836 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002837 }
Christopher Tate7926a692011-07-11 11:31:57 -07002838
Christopher Tateb0628bf2011-06-02 15:08:13 -07002839 } catch (IOException e) {
2840 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002841 } finally {
2842 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002843 // flush after every package
2844 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002845 if (pipes != null) {
2846 if (pipes[0] != null) pipes[0].close();
2847 if (pipes[1] != null) pipes[1].close();
2848 }
Christopher Tate7926a692011-07-11 11:31:57 -07002849 } catch (IOException e) {
2850 Slog.w(TAG, "Error bringing down backup stack");
2851 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002852 }
2853 } else {
2854 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2855 }
2856 tearDown(pkg);
2857 }
2858
Christopher Tate79ec80d2011-06-24 14:58:49 -07002859 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2860 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2861 final String appSourceDir = pkg.applicationInfo.sourceDir;
2862 final String apkDir = new File(appSourceDir).getParent();
2863 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2864 apkDir, appSourceDir, output);
2865
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002866 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2867 // doesn't have access to external storage.
2868
Christopher Tate79ec80d2011-06-24 14:58:49 -07002869 // Save associated .obb content if it exists and we did save the apk
2870 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002871 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2872 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002873 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002874 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002875 File[] obbFiles = obbDir.listFiles();
2876 if (obbFiles != null) {
2877 final String obbDirName = obbDir.getAbsolutePath();
2878 for (File obb : obbFiles) {
2879 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2880 obbDirName, obb.getAbsolutePath(), output);
2881 }
2882 }
2883 }
2884 }
2885
Christopher Tate6853fcf2011-08-10 17:52:21 -07002886 private void finalizeBackup(OutputStream out) {
2887 try {
2888 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2889 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2890 out.write(eof);
2891 } catch (IOException e) {
2892 Slog.w(TAG, "Error attempting to finalize backup stream");
2893 }
2894 }
2895
Christopher Tate4a627c72011-04-01 14:43:32 -07002896 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2897 throws IOException {
2898 // Manifest format. All data are strings ending in LF:
2899 // BACKUP_MANIFEST_VERSION, currently 1
2900 //
2901 // Version 1:
2902 // package name
2903 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002904 // platform versionCode
2905 // getInstallerPackageName() for this package (maybe empty)
2906 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002907 // number of signatures == N
2908 // N*: signature byte array in ascii format per Signature.toCharsString()
2909 StringBuilder builder = new StringBuilder(4096);
2910 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2911
2912 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2913 printer.println(pkg.packageName);
2914 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002915 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2916
2917 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2918 printer.println((installerName != null) ? installerName : "");
2919
Christopher Tate4a627c72011-04-01 14:43:32 -07002920 printer.println(withApk ? "1" : "0");
2921 if (pkg.signatures == null) {
2922 printer.println("0");
2923 } else {
2924 printer.println(Integer.toString(pkg.signatures.length));
2925 for (Signature sig : pkg.signatures) {
2926 printer.println(sig.toCharsString());
2927 }
2928 }
2929
2930 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002931 outstream.write(builder.toString().getBytes());
2932 outstream.close();
2933 }
2934
2935 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002936 if (pkg != null) {
2937 final ApplicationInfo app = pkg.applicationInfo;
2938 if (app != null) {
2939 try {
2940 // unbind and tidy up even on timeout or failure, just in case
2941 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002942
Christopher Tateb0628bf2011-06-02 15:08:13 -07002943 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002944 if (app.uid != Process.SYSTEM_UID
2945 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002946 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002947 mActivityManager.killApplicationProcess(app.processName, app.uid);
2948 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002949 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002950 }
2951 } catch (RemoteException e) {
2952 Slog.d(TAG, "Lost app trying to shut down");
2953 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002954 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002955 }
2956 }
2957
2958 // wrappers for observer use
2959 void sendStartBackup() {
2960 if (mObserver != null) {
2961 try {
2962 mObserver.onStartBackup();
2963 } catch (RemoteException e) {
2964 Slog.w(TAG, "full backup observer went away: startBackup");
2965 mObserver = null;
2966 }
2967 }
2968 }
2969
2970 void sendOnBackupPackage(String name) {
2971 if (mObserver != null) {
2972 try {
2973 // TODO: use a more user-friendly name string
2974 mObserver.onBackupPackage(name);
2975 } catch (RemoteException e) {
2976 Slog.w(TAG, "full backup observer went away: backupPackage");
2977 mObserver = null;
2978 }
2979 }
2980 }
2981
2982 void sendEndBackup() {
2983 if (mObserver != null) {
2984 try {
2985 mObserver.onEndBackup();
2986 } catch (RemoteException e) {
2987 Slog.w(TAG, "full backup observer went away: endBackup");
2988 mObserver = null;
2989 }
2990 }
2991 }
2992 }
2993
2994
Christopher Tate75a99702011-05-18 16:28:19 -07002995 // ----- Full restore from a file/socket -----
2996
2997 // Description of a file in the restore datastream
2998 static class FileMetadata {
2999 String packageName; // name of the owning app
3000 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07003001 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07003002 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
3003 String path; // subpath within the semantic domain
3004 long mode; // e.g. 0666 (actually int)
3005 long mtime; // last mod time, UTC time_t (actually int)
3006 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003007
3008 @Override
3009 public String toString() {
3010 StringBuilder sb = new StringBuilder(128);
3011 sb.append("FileMetadata{");
3012 sb.append(packageName); sb.append(',');
3013 sb.append(type); sb.append(',');
3014 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3015 sb.append(size);
3016 sb.append('}');
3017 return sb.toString();
3018 }
Christopher Tate75a99702011-05-18 16:28:19 -07003019 }
3020
3021 enum RestorePolicy {
3022 IGNORE,
3023 ACCEPT,
3024 ACCEPT_IF_APK
3025 }
3026
Christopher Tate294b5122013-02-19 14:08:59 -08003027 class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
Christopher Tate75a99702011-05-18 16:28:19 -07003028 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07003029 String mCurrentPassword;
3030 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003031 IFullBackupRestoreObserver mObserver;
3032 AtomicBoolean mLatchObject;
3033 IBackupAgent mAgent;
3034 String mAgentPackage;
3035 ApplicationInfo mTargetApp;
Christopher Tate294b5122013-02-19 14:08:59 -08003036 FullBackupObbConnection mObbConnection = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003037 ParcelFileDescriptor[] mPipes = null;
3038
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003039 long mBytes;
3040
Christopher Tate75a99702011-05-18 16:28:19 -07003041 // possible handling states for a given package in the restore dataset
3042 final HashMap<String, RestorePolicy> mPackagePolicies
3043 = new HashMap<String, RestorePolicy>();
3044
3045 // installer package names for each encountered app, derived from the manifests
3046 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3047
3048 // Signatures for a given package found in its manifest file
3049 final HashMap<String, Signature[]> mManifestSignatures
3050 = new HashMap<String, Signature[]>();
3051
3052 // Packages we've already wiped data on when restoring their first file
3053 final HashSet<String> mClearedPackages = new HashSet<String>();
3054
Christopher Tate728a1c42011-07-28 18:03:03 -07003055 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003056 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07003057 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07003058 mCurrentPassword = curPassword;
3059 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003060 mObserver = observer;
3061 mLatchObject = latch;
3062 mAgent = null;
3063 mAgentPackage = null;
3064 mTargetApp = null;
Christopher Tate294b5122013-02-19 14:08:59 -08003065 mObbConnection = new FullBackupObbConnection();
Christopher Tate75a99702011-05-18 16:28:19 -07003066
3067 // Which packages we've already wiped data on. We prepopulate this
3068 // with a whitelist of packages known to be unclearable.
3069 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07003070 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07003071
Christopher Tate75a99702011-05-18 16:28:19 -07003072 }
3073
3074 class RestoreFileRunnable implements Runnable {
3075 IBackupAgent mAgent;
3076 FileMetadata mInfo;
3077 ParcelFileDescriptor mSocket;
3078 int mToken;
3079
3080 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3081 ParcelFileDescriptor socket, int token) throws IOException {
3082 mAgent = agent;
3083 mInfo = info;
3084 mToken = token;
3085
3086 // This class is used strictly for process-local binder invocations. The
3087 // semantics of ParcelFileDescriptor differ in this case; in particular, we
3088 // do not automatically get a 'dup'ed descriptor that we can can continue
3089 // to use asynchronously from the caller. So, we make sure to dup it ourselves
3090 // before proceeding to do the restore.
3091 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3092 }
3093
3094 @Override
3095 public void run() {
3096 try {
3097 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3098 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3099 mToken, mBackupManagerBinder);
3100 } catch (RemoteException e) {
3101 // never happens; this is used strictly for local binder calls
3102 }
3103 }
3104 }
3105
3106 @Override
3107 public void run() {
3108 Slog.i(TAG, "--- Performing full-dataset restore ---");
Christopher Tate294b5122013-02-19 14:08:59 -08003109 mObbConnection.establish();
Christopher Tate75a99702011-05-18 16:28:19 -07003110 sendStartRestore();
3111
Christopher Tateb0628bf2011-06-02 15:08:13 -07003112 // Are we able to restore shared-storage data?
3113 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08003114 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07003115 }
3116
Christopher Tate2efd2db2011-07-19 16:32:49 -07003117 FileInputStream rawInStream = null;
3118 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003119 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07003120 if (hasBackupPassword()) {
3121 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
3122 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3123 return;
3124 }
3125 }
3126
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003127 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003128 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003129 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3130 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003131
3132 // First, parse out the unencrypted/uncompressed header
3133 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003134 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003135 final InputStream in;
3136
3137 boolean okay = false;
3138 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3139 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003140 rawDataIn.readFully(streamHeader);
3141 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3142 if (Arrays.equals(magicBytes, streamHeader)) {
3143 // okay, header looks good. now parse out the rest of the fields.
3144 String s = readHeaderLine(rawInStream);
3145 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3146 // okay, it's a version we recognize
3147 s = readHeaderLine(rawInStream);
3148 compressed = (Integer.parseInt(s) != 0);
3149 s = readHeaderLine(rawInStream);
3150 if (s.equals("none")) {
3151 // no more header to parse; we're good to go
3152 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003153 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003154 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3155 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003156 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003157 }
3158 } else Slog.w(TAG, "Archive is encrypted but no password given");
3159 } else Slog.w(TAG, "Wrong header version: " + s);
3160 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003161
3162 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003163 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003164 return;
3165 }
3166
3167 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003168 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003169
3170 boolean didRestore;
3171 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003172 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003173 } while (didRestore);
3174
Christopher Tatec58efa62011-08-01 19:20:14 -07003175 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003176 } catch (IOException e) {
3177 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003178 } finally {
3179 tearDownPipes();
3180 tearDownAgent(mTargetApp);
3181
3182 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003183 if (rawDataIn != null) rawDataIn.close();
3184 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003185 mInputFile.close();
3186 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003187 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003188 /* nothing we can do about this */
3189 }
3190 synchronized (mCurrentOpLock) {
3191 mCurrentOperations.clear();
3192 }
3193 synchronized (mLatchObject) {
3194 mLatchObject.set(true);
3195 mLatchObject.notifyAll();
3196 }
Christopher Tate294b5122013-02-19 14:08:59 -08003197 mObbConnection.tearDown();
Christopher Tate75a99702011-05-18 16:28:19 -07003198 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003199 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003200 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003201 }
3202 }
3203
Christopher Tate7bdb0962011-07-13 19:30:21 -07003204 String readHeaderLine(InputStream in) throws IOException {
3205 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003206 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003207 while ((c = in.read()) >= 0) {
3208 if (c == '\n') break; // consume and discard the newlines
3209 buffer.append((char)c);
3210 }
3211 return buffer.toString();
3212 }
3213
Christopher Tate2efd2db2011-07-19 16:32:49 -07003214 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3215 InputStream result = null;
3216 try {
3217 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3218
3219 String userSaltHex = readHeaderLine(rawInStream); // 5
3220 byte[] userSalt = hexToByteArray(userSaltHex);
3221
3222 String ckSaltHex = readHeaderLine(rawInStream); // 6
3223 byte[] ckSalt = hexToByteArray(ckSaltHex);
3224
3225 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3226 String userIvHex = readHeaderLine(rawInStream); // 8
3227
3228 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3229
3230 // decrypt the master key blob
3231 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003232 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003233 rounds);
3234 byte[] IV = hexToByteArray(userIvHex);
3235 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3236 c.init(Cipher.DECRYPT_MODE,
3237 new SecretKeySpec(userKey.getEncoded(), "AES"),
3238 ivSpec);
3239 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3240 byte[] mkBlob = c.doFinal(mkCipher);
3241
3242 // first, the master key IV
3243 int offset = 0;
3244 int len = mkBlob[offset++];
3245 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3246 offset += len;
3247 // then the master key itself
3248 len = mkBlob[offset++];
3249 byte[] mk = Arrays.copyOfRange(mkBlob,
3250 offset, offset + len);
3251 offset += len;
3252 // and finally the master key checksum hash
3253 len = mkBlob[offset++];
3254 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3255 offset, offset + len);
3256
3257 // now validate the decrypted master key against the checksum
3258 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3259 if (Arrays.equals(calculatedCk, mkChecksum)) {
3260 ivSpec = new IvParameterSpec(IV);
3261 c.init(Cipher.DECRYPT_MODE,
3262 new SecretKeySpec(mk, "AES"),
3263 ivSpec);
3264 // Only if all of the above worked properly will 'result' be assigned
3265 result = new CipherInputStream(rawInStream, c);
3266 } else Slog.w(TAG, "Incorrect password");
3267 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3268 } catch (InvalidAlgorithmParameterException e) {
3269 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3270 } catch (BadPaddingException e) {
3271 // This case frequently occurs when the wrong password is used to decrypt
3272 // the master key. Use the identical "incorrect password" log text as is
3273 // used in the checksum failure log in order to avoid providing additional
3274 // information to an attacker.
3275 Slog.w(TAG, "Incorrect password");
3276 } catch (IllegalBlockSizeException e) {
3277 Slog.w(TAG, "Invalid block size in master key");
3278 } catch (NoSuchAlgorithmException e) {
3279 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3280 } catch (NoSuchPaddingException e) {
3281 Slog.e(TAG, "Needed padding mechanism unavailable!");
3282 } catch (InvalidKeyException e) {
3283 Slog.w(TAG, "Illegal password; aborting");
3284 } catch (NumberFormatException e) {
3285 Slog.w(TAG, "Can't parse restore data header");
3286 } catch (IOException e) {
3287 Slog.w(TAG, "Can't read input header");
3288 }
3289
3290 return result;
3291 }
3292
Christopher Tate75a99702011-05-18 16:28:19 -07003293 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3294 FileMetadata info;
3295 try {
3296 info = readTarHeaders(instream);
3297 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003298 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003299 dumpFileMetadata(info);
3300 }
3301
3302 final String pkg = info.packageName;
3303 if (!pkg.equals(mAgentPackage)) {
3304 // okay, change in package; set up our various
3305 // bookkeeping if we haven't seen it yet
3306 if (!mPackagePolicies.containsKey(pkg)) {
3307 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3308 }
3309
3310 // Clean up the previous agent relationship if necessary,
3311 // and let the observer know we're considering a new app.
3312 if (mAgent != null) {
3313 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3314 tearDownPipes();
3315 tearDownAgent(mTargetApp);
3316 mTargetApp = null;
3317 mAgentPackage = null;
3318 }
3319 }
3320
3321 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3322 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3323 mPackageInstallers.put(pkg, info.installerPackageName);
3324 // We've read only the manifest content itself at this point,
3325 // so consume the footer before looping around to the next
3326 // input file
3327 skipTarPadding(info.size, instream);
3328 sendOnRestorePackage(pkg);
3329 } else {
3330 // Non-manifest, so it's actual file data. Is this a package
3331 // we're ignoring?
3332 boolean okay = true;
3333 RestorePolicy policy = mPackagePolicies.get(pkg);
3334 switch (policy) {
3335 case IGNORE:
3336 okay = false;
3337 break;
3338
3339 case ACCEPT_IF_APK:
3340 // If we're in accept-if-apk state, then the first file we
3341 // see MUST be the apk.
3342 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3343 if (DEBUG) Slog.d(TAG, "APK file; installing");
3344 // Try to install the app.
3345 String installerName = mPackageInstallers.get(pkg);
3346 okay = installApk(info, installerName, instream);
3347 // good to go; promote to ACCEPT
3348 mPackagePolicies.put(pkg, (okay)
3349 ? RestorePolicy.ACCEPT
3350 : RestorePolicy.IGNORE);
3351 // At this point we've consumed this file entry
3352 // ourselves, so just strip the tar footer and
3353 // go on to the next file in the input stream
3354 skipTarPadding(info.size, instream);
3355 return true;
3356 } else {
3357 // File data before (or without) the apk. We can't
3358 // handle it coherently in this case so ignore it.
3359 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3360 okay = false;
3361 }
3362 break;
3363
3364 case ACCEPT:
3365 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3366 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3367 // we can take the data without the apk, so we
3368 // *want* to do so. skip the apk by declaring this
3369 // one file not-okay without changing the restore
3370 // policy for the package.
3371 okay = false;
3372 }
3373 break;
3374
3375 default:
3376 // Something has gone dreadfully wrong when determining
3377 // the restore policy from the manifest. Ignore the
3378 // rest of this package's data.
3379 Slog.e(TAG, "Invalid policy from manifest");
3380 okay = false;
3381 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3382 break;
3383 }
3384
3385 // If the policy is satisfied, go ahead and set up to pipe the
3386 // data to the agent.
3387 if (DEBUG && okay && mAgent != null) {
3388 Slog.i(TAG, "Reusing existing agent instance");
3389 }
3390 if (okay && mAgent == null) {
3391 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3392
3393 try {
3394 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3395
3396 // If we haven't sent any data to this app yet, we probably
3397 // need to clear it first. Check that.
3398 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003399 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003400 // responsible for coherently managing a full
3401 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003402 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003403 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3404 clearApplicationDataSynchronous(pkg);
3405 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003406 if (DEBUG) Slog.d(TAG, "backup agent ("
3407 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003408 }
3409 mClearedPackages.add(pkg);
3410 } else {
3411 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3412 }
3413
3414 // All set; now set up the IPC and launch the agent
3415 setUpPipes();
3416 mAgent = bindToAgentSynchronous(mTargetApp,
3417 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3418 mAgentPackage = pkg;
3419 } catch (IOException e) {
3420 // fall through to error handling
3421 } catch (NameNotFoundException e) {
3422 // fall through to error handling
3423 }
3424
3425 if (mAgent == null) {
3426 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3427 okay = false;
3428 tearDownPipes();
3429 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3430 }
3431 }
3432
3433 // Sanity check: make sure we never give data to the wrong app. This
3434 // should never happen but a little paranoia here won't go amiss.
3435 if (okay && !pkg.equals(mAgentPackage)) {
3436 Slog.e(TAG, "Restoring data for " + pkg
3437 + " but agent is for " + mAgentPackage);
3438 okay = false;
3439 }
3440
3441 // At this point we have an agent ready to handle the full
3442 // restore data as well as a pipe for sending data to
3443 // that agent. Tell the agent to start reading from the
3444 // pipe.
3445 if (okay) {
3446 boolean agentSuccess = true;
3447 long toCopy = info.size;
3448 final int token = generateToken();
3449 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07003450 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate294b5122013-02-19 14:08:59 -08003451 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3452 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3453 + " : " + info.path);
3454 mObbConnection.restoreObbFile(pkg, mPipes[0],
3455 info.size, info.type, info.path, info.mode,
3456 info.mtime, token, mBackupManagerBinder);
Christopher Tate75a99702011-05-18 16:28:19 -07003457 } else {
Christopher Tate294b5122013-02-19 14:08:59 -08003458 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3459 + info.path);
3460 // fire up the app's agent listening on the socket. If
3461 // the agent is running in the system process we can't
3462 // just invoke it asynchronously, so we provide a thread
3463 // for it here.
3464 if (mTargetApp.processName.equals("system")) {
3465 Slog.d(TAG, "system process agent - spinning a thread");
3466 RestoreFileRunnable runner = new RestoreFileRunnable(
3467 mAgent, info, mPipes[0], token);
3468 new Thread(runner).start();
3469 } else {
3470 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3471 info.domain, info.path, info.mode, info.mtime,
3472 token, mBackupManagerBinder);
3473 }
Christopher Tate75a99702011-05-18 16:28:19 -07003474 }
3475 } catch (IOException e) {
3476 // couldn't dup the socket for a process-local restore
3477 Slog.d(TAG, "Couldn't establish restore");
3478 agentSuccess = false;
3479 okay = false;
3480 } catch (RemoteException e) {
Christopher Tate294b5122013-02-19 14:08:59 -08003481 // whoops, remote entity went away. We'll eat the content
Christopher Tate75a99702011-05-18 16:28:19 -07003482 // ourselves, then, and not copy it over.
3483 Slog.e(TAG, "Agent crashed during full restore");
3484 agentSuccess = false;
3485 okay = false;
3486 }
3487
3488 // Copy over the data if the agent is still good
3489 if (okay) {
3490 boolean pipeOkay = true;
3491 FileOutputStream pipe = new FileOutputStream(
3492 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003493 while (toCopy > 0) {
3494 int toRead = (toCopy > buffer.length)
3495 ? buffer.length : (int)toCopy;
3496 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003497 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003498 if (nRead <= 0) break;
3499 toCopy -= nRead;
3500
3501 // send it to the output pipe as long as things
3502 // are still good
3503 if (pipeOkay) {
3504 try {
3505 pipe.write(buffer, 0, nRead);
3506 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003507 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003508 pipeOkay = false;
3509 }
3510 }
3511 }
3512
3513 // done sending that file! Now we just need to consume
3514 // the delta from info.size to the end of block.
3515 skipTarPadding(info.size, instream);
3516
3517 // and now that we've sent it all, wait for the remote
3518 // side to acknowledge receipt
3519 agentSuccess = waitUntilOperationComplete(token);
3520 }
3521
3522 // okay, if the remote end failed at any point, deal with
3523 // it by ignoring the rest of the restore on it
3524 if (!agentSuccess) {
3525 mBackupHandler.removeMessages(MSG_TIMEOUT);
3526 tearDownPipes();
3527 tearDownAgent(mTargetApp);
3528 mAgent = null;
3529 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3530 }
3531 }
3532
3533 // Problems setting up the agent communication, or an already-
3534 // ignored package: skip to the next tar stream entry by
3535 // reading and discarding this file.
3536 if (!okay) {
3537 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3538 long bytesToConsume = (info.size + 511) & ~511;
3539 while (bytesToConsume > 0) {
3540 int toRead = (bytesToConsume > buffer.length)
3541 ? buffer.length : (int)bytesToConsume;
3542 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003543 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003544 if (nRead <= 0) break;
3545 bytesToConsume -= nRead;
3546 }
3547 }
3548 }
3549 }
3550 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003551 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003552 // treat as EOF
3553 info = null;
3554 }
3555
3556 return (info != null);
3557 }
3558
3559 void setUpPipes() throws IOException {
3560 mPipes = ParcelFileDescriptor.createPipe();
3561 }
3562
3563 void tearDownPipes() {
3564 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003565 try {
3566 mPipes[0].close();
3567 mPipes[0] = null;
3568 mPipes[1].close();
3569 mPipes[1] = null;
3570 } catch (IOException e) {
3571 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003572 }
3573 mPipes = null;
3574 }
3575 }
3576
3577 void tearDownAgent(ApplicationInfo app) {
3578 if (mAgent != null) {
3579 try {
3580 // unbind and tidy up even on timeout or failure, just in case
3581 mActivityManager.unbindBackupAgent(app);
3582
3583 // The agent was running with a stub Application object, so shut it down.
3584 // !!! We hardcode the confirmation UI's package name here rather than use a
3585 // manifest flag! TODO something less direct.
3586 if (app.uid != Process.SYSTEM_UID
3587 && !app.packageName.equals("com.android.backupconfirm")) {
3588 if (DEBUG) Slog.d(TAG, "Killing host process");
3589 mActivityManager.killApplicationProcess(app.processName, app.uid);
3590 } else {
3591 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3592 }
3593 } catch (RemoteException e) {
3594 Slog.d(TAG, "Lost app trying to shut down");
3595 }
3596 mAgent = null;
3597 }
3598 }
3599
3600 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3601 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003602 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003603 int mResult;
3604
3605 public void reset() {
3606 synchronized (mDone) {
3607 mDone.set(false);
3608 }
3609 }
3610
3611 public void waitForCompletion() {
3612 synchronized (mDone) {
3613 while (mDone.get() == false) {
3614 try {
3615 mDone.wait();
3616 } catch (InterruptedException e) { }
3617 }
3618 }
3619 }
3620
3621 int getResult() {
3622 return mResult;
3623 }
3624
3625 @Override
3626 public void packageInstalled(String packageName, int returnCode)
3627 throws RemoteException {
3628 synchronized (mDone) {
3629 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003630 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003631 mDone.set(true);
3632 mDone.notifyAll();
3633 }
3634 }
3635 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003636
3637 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3638 final AtomicBoolean mDone = new AtomicBoolean();
3639 int mResult;
3640
3641 public void reset() {
3642 synchronized (mDone) {
3643 mDone.set(false);
3644 }
3645 }
3646
3647 public void waitForCompletion() {
3648 synchronized (mDone) {
3649 while (mDone.get() == false) {
3650 try {
3651 mDone.wait();
3652 } catch (InterruptedException e) { }
3653 }
3654 }
3655 }
3656
3657 @Override
3658 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3659 synchronized (mDone) {
3660 mResult = returnCode;
3661 mDone.set(true);
3662 mDone.notifyAll();
3663 }
3664 }
3665 }
3666
Christopher Tate75a99702011-05-18 16:28:19 -07003667 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003668 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003669
3670 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3671 boolean okay = true;
3672
3673 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3674
3675 // The file content is an .apk file. Copy it out to a staging location and
3676 // attempt to install it.
3677 File apkFile = new File(mDataDir, info.packageName);
3678 try {
3679 FileOutputStream apkStream = new FileOutputStream(apkFile);
3680 byte[] buffer = new byte[32 * 1024];
3681 long size = info.size;
3682 while (size > 0) {
3683 long toRead = (buffer.length < size) ? buffer.length : size;
3684 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003685 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003686 apkStream.write(buffer, 0, didRead);
3687 size -= didRead;
3688 }
3689 apkStream.close();
3690
3691 // make sure the installer can read it
3692 apkFile.setReadable(true, false);
3693
3694 // Now install it
3695 Uri packageUri = Uri.fromFile(apkFile);
3696 mInstallObserver.reset();
3697 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003698 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3699 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003700 mInstallObserver.waitForCompletion();
3701
3702 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3703 // The only time we continue to accept install of data even if the
3704 // apk install failed is if we had already determined that we could
3705 // accept the data regardless.
3706 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3707 okay = false;
3708 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003709 } else {
3710 // Okay, the install succeeded. Make sure it was the right app.
3711 boolean uninstall = false;
3712 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3713 Slog.w(TAG, "Restore stream claimed to include apk for "
3714 + info.packageName + " but apk was really "
3715 + mInstallObserver.mPackageName);
3716 // delete the package we just put in place; it might be fraudulent
3717 okay = false;
3718 uninstall = true;
3719 } else {
3720 try {
3721 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3722 PackageManager.GET_SIGNATURES);
3723 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3724 Slog.w(TAG, "Restore stream contains apk of package "
3725 + info.packageName + " but it disallows backup/restore");
3726 okay = false;
3727 } else {
3728 // So far so good -- do the signatures match the manifest?
3729 Signature[] sigs = mManifestSignatures.get(info.packageName);
3730 if (!signaturesMatch(sigs, pkg)) {
3731 Slog.w(TAG, "Installed app " + info.packageName
3732 + " signatures do not match restore manifest");
3733 okay = false;
3734 uninstall = true;
3735 }
3736 }
3737 } catch (NameNotFoundException e) {
3738 Slog.w(TAG, "Install of package " + info.packageName
3739 + " succeeded but now not found");
3740 okay = false;
3741 }
3742 }
3743
3744 // If we're not okay at this point, we need to delete the package
3745 // that we just installed.
3746 if (uninstall) {
3747 mDeleteObserver.reset();
3748 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3749 mDeleteObserver, 0);
3750 mDeleteObserver.waitForCompletion();
3751 }
Christopher Tate75a99702011-05-18 16:28:19 -07003752 }
3753 } catch (IOException e) {
3754 Slog.e(TAG, "Unable to transcribe restored apk for install");
3755 okay = false;
3756 } finally {
3757 apkFile.delete();
3758 }
3759
3760 return okay;
3761 }
3762
3763 // Given an actual file content size, consume the post-content padding mandated
3764 // by the tar format.
3765 void skipTarPadding(long size, InputStream instream) throws IOException {
3766 long partial = (size + 512) % 512;
3767 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003768 final int needed = 512 - (int)partial;
3769 byte[] buffer = new byte[needed];
3770 if (readExactly(instream, buffer, 0, needed) == needed) {
3771 mBytes += needed;
3772 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003773 }
3774 }
3775
3776 // Returns a policy constant; takes a buffer arg to reduce memory churn
3777 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3778 throws IOException {
3779 // Fail on suspiciously large manifest files
3780 if (info.size > 64 * 1024) {
3781 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3782 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003783
Christopher Tate75a99702011-05-18 16:28:19 -07003784 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003785 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3786 mBytes += info.size;
3787 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003788
3789 RestorePolicy policy = RestorePolicy.IGNORE;
3790 String[] str = new String[1];
3791 int offset = 0;
3792
3793 try {
3794 offset = extractLine(buffer, offset, str);
3795 int version = Integer.parseInt(str[0]);
3796 if (version == BACKUP_MANIFEST_VERSION) {
3797 offset = extractLine(buffer, offset, str);
3798 String manifestPackage = str[0];
3799 // TODO: handle <original-package>
3800 if (manifestPackage.equals(info.packageName)) {
3801 offset = extractLine(buffer, offset, str);
3802 version = Integer.parseInt(str[0]); // app version
3803 offset = extractLine(buffer, offset, str);
3804 int platformVersion = Integer.parseInt(str[0]);
3805 offset = extractLine(buffer, offset, str);
3806 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3807 offset = extractLine(buffer, offset, str);
3808 boolean hasApk = str[0].equals("1");
3809 offset = extractLine(buffer, offset, str);
3810 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003811 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003812 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003813 for (int i = 0; i < numSigs; i++) {
3814 offset = extractLine(buffer, offset, str);
3815 sigs[i] = new Signature(str[0]);
3816 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003817 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003818
3819 // Okay, got the manifest info we need...
3820 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003821 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3822 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003823 // Fall through to IGNORE if the app explicitly disallows backup
3824 final int flags = pkgInfo.applicationInfo.flags;
3825 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003826 // Restore system-uid-space packages only if they have
3827 // defined a custom backup agent
3828 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3829 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3830 // Verify signatures against any installed version; if they
3831 // don't match, then we fall though and ignore the data. The
3832 // signatureMatch() method explicitly ignores the signature
3833 // check for packages installed on the system partition, because
3834 // such packages are signed with the platform cert instead of
3835 // the app developer's cert, so they're different on every
3836 // device.
3837 if (signaturesMatch(sigs, pkgInfo)) {
3838 if (pkgInfo.versionCode >= version) {
3839 Slog.i(TAG, "Sig + version match; taking data");
3840 policy = RestorePolicy.ACCEPT;
3841 } else {
3842 // The data is from a newer version of the app than
3843 // is presently installed. That means we can only
3844 // use it if the matching apk is also supplied.
3845 Slog.d(TAG, "Data version " + version
3846 + " is newer than installed version "
3847 + pkgInfo.versionCode + " - requiring apk");
3848 policy = RestorePolicy.ACCEPT_IF_APK;
3849 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003850 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003851 Slog.w(TAG, "Restore manifest signatures do not match "
3852 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003853 }
Christopher Tate75a99702011-05-18 16:28:19 -07003854 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003855 Slog.w(TAG, "Package " + info.packageName
3856 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003857 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003858 } else {
3859 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3860 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003861 }
3862 } catch (NameNotFoundException e) {
3863 // Okay, the target app isn't installed. We can process
3864 // the restore properly only if the dataset provides the
3865 // apk file and we can successfully install it.
3866 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3867 + " not installed; requiring apk in dataset");
3868 policy = RestorePolicy.ACCEPT_IF_APK;
3869 }
3870
3871 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3872 Slog.i(TAG, "Cannot restore package " + info.packageName
3873 + " without the matching .apk");
3874 }
3875 } else {
3876 Slog.i(TAG, "Missing signature on backed-up package "
3877 + info.packageName);
3878 }
3879 } else {
3880 Slog.i(TAG, "Expected package " + info.packageName
3881 + " but restore manifest claims " + manifestPackage);
3882 }
3883 } else {
3884 Slog.i(TAG, "Unknown restore manifest version " + version
3885 + " for package " + info.packageName);
3886 }
3887 } catch (NumberFormatException e) {
3888 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003889 } catch (IllegalArgumentException e) {
3890 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003891 }
3892
3893 return policy;
3894 }
3895
3896 // Builds a line from a byte buffer starting at 'offset', and returns
3897 // the index of the next unconsumed data in the buffer.
3898 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3899 final int end = buffer.length;
3900 if (offset >= end) throw new IOException("Incomplete data");
3901
3902 int pos;
3903 for (pos = offset; pos < end; pos++) {
3904 byte c = buffer[pos];
3905 // at LF we declare end of line, and return the next char as the
3906 // starting point for the next time through
3907 if (c == '\n') {
3908 break;
3909 }
3910 }
3911 outStr[0] = new String(buffer, offset, pos - offset);
3912 pos++; // may be pointing an extra byte past the end but that's okay
3913 return pos;
3914 }
3915
3916 void dumpFileMetadata(FileMetadata info) {
3917 if (DEBUG) {
3918 StringBuilder b = new StringBuilder(128);
3919
3920 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003921 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003922 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3923 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3924 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3925 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3926 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3927 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3928 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3929 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3930 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3931 b.append(String.format(" %9d ", info.size));
3932
3933 Date stamp = new Date(info.mtime);
3934 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3935
3936 b.append(info.packageName);
3937 b.append(" :: ");
3938 b.append(info.domain);
3939 b.append(" :: ");
3940 b.append(info.path);
3941
3942 Slog.i(TAG, b.toString());
3943 }
3944 }
3945 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3946 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3947 byte[] block = new byte[512];
3948 FileMetadata info = null;
3949
3950 boolean gotHeader = readTarHeader(instream, block);
3951 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003952 try {
3953 // okay, presume we're okay, and extract the various metadata
3954 info = new FileMetadata();
3955 info.size = extractRadix(block, 124, 12, 8);
3956 info.mtime = extractRadix(block, 136, 12, 8);
3957 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003958
Christopher Tate2efd2db2011-07-19 16:32:49 -07003959 info.path = extractString(block, 345, 155); // prefix
3960 String path = extractString(block, 0, 100);
3961 if (path.length() > 0) {
3962 if (info.path.length() > 0) info.path += '/';
3963 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003964 }
Christopher Tate75a99702011-05-18 16:28:19 -07003965
Christopher Tate2efd2db2011-07-19 16:32:49 -07003966 // tar link indicator field: 1 byte at offset 156 in the header.
3967 int typeChar = block[156];
3968 if (typeChar == 'x') {
3969 // pax extended header, so we need to read that
3970 gotHeader = readPaxExtendedHeader(instream, info);
3971 if (gotHeader) {
3972 // and after a pax extended header comes another real header -- read
3973 // that to find the real file type
3974 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003975 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003976 if (!gotHeader) throw new IOException("Bad or missing pax header");
3977
3978 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003979 }
Christopher Tate75a99702011-05-18 16:28:19 -07003980
Christopher Tate2efd2db2011-07-19 16:32:49 -07003981 switch (typeChar) {
3982 case '0': info.type = BackupAgent.TYPE_FILE; break;
3983 case '5': {
3984 info.type = BackupAgent.TYPE_DIRECTORY;
3985 if (info.size != 0) {
3986 Slog.w(TAG, "Directory entry with nonzero size in header");
3987 info.size = 0;
3988 }
3989 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003990 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003991 case 0: {
3992 // presume EOF
3993 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3994 return null;
3995 }
3996 default: {
3997 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3998 throw new IOException("Unknown entity type " + typeChar);
3999 }
Christopher Tate75a99702011-05-18 16:28:19 -07004000 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004001
4002 // Parse out the path
4003 //
4004 // first: apps/shared/unrecognized
4005 if (FullBackup.SHARED_PREFIX.regionMatches(0,
4006 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4007 // File in shared storage. !!! TODO: implement this.
4008 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08004009 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004010 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4011 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4012 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4013 info.path, 0, FullBackup.APPS_PREFIX.length())) {
4014 // App content! Parse out the package name and domain
4015
4016 // strip the apps/ prefix
4017 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4018
4019 // extract the package name
4020 int slash = info.path.indexOf('/');
4021 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4022 info.packageName = info.path.substring(0, slash);
4023 info.path = info.path.substring(slash+1);
4024
4025 // if it's a manifest we're done, otherwise parse out the domains
4026 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4027 slash = info.path.indexOf('/');
4028 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4029 info.domain = info.path.substring(0, slash);
Christopher Tate2efd2db2011-07-19 16:32:49 -07004030 info.path = info.path.substring(slash + 1);
4031 }
4032 }
4033 } catch (IOException e) {
4034 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07004035 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07004036 HEXLOG(block);
4037 }
4038 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07004039 }
4040 }
4041 return info;
4042 }
4043
Christopher Tate2efd2db2011-07-19 16:32:49 -07004044 private void HEXLOG(byte[] block) {
4045 int offset = 0;
4046 int todo = block.length;
4047 StringBuilder buf = new StringBuilder(64);
4048 while (todo > 0) {
4049 buf.append(String.format("%04x ", offset));
4050 int numThisLine = (todo > 16) ? 16 : todo;
4051 for (int i = 0; i < numThisLine; i++) {
4052 buf.append(String.format("%02x ", block[offset+i]));
4053 }
4054 Slog.i("hexdump", buf.toString());
4055 buf.setLength(0);
4056 todo -= numThisLine;
4057 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07004058 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004059 }
4060
Christopher Tate6853fcf2011-08-10 17:52:21 -07004061 // Read exactly the given number of bytes into a buffer at the stated offset.
4062 // Returns false if EOF is encountered before the requested number of bytes
4063 // could be read.
4064 int readExactly(InputStream in, byte[] buffer, int offset, int size)
4065 throws IOException {
4066 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4067
4068 int soFar = 0;
4069 while (soFar < size) {
4070 int nRead = in.read(buffer, offset + soFar, size - soFar);
4071 if (nRead <= 0) {
4072 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4073 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004074 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004075 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004076 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004077 return soFar;
4078 }
4079
4080 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4081 final int got = readExactly(instream, block, 0, 512);
4082 if (got == 0) return false; // Clean EOF
4083 if (got < 512) throw new IOException("Unable to read full block header");
4084 mBytes += 512;
4085 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07004086 }
4087
4088 // overwrites 'info' fields based on the pax extended header
4089 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4090 throws IOException {
4091 // We should never see a pax extended header larger than this
4092 if (info.size > 32*1024) {
4093 Slog.w(TAG, "Suspiciously large pax header size " + info.size
4094 + " - aborting");
4095 throw new IOException("Sanity failure: pax header size " + info.size);
4096 }
4097
4098 // read whole blocks, not just the content size
4099 int numBlocks = (int)((info.size + 511) >> 9);
4100 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07004101 if (readExactly(instream, data, 0, data.length) < data.length) {
4102 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07004103 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004104 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07004105
4106 final int contentSize = (int) info.size;
4107 int offset = 0;
4108 do {
4109 // extract the line at 'offset'
4110 int eol = offset+1;
4111 while (eol < contentSize && data[eol] != ' ') eol++;
4112 if (eol >= contentSize) {
4113 // error: we just hit EOD looking for the end of the size field
4114 throw new IOException("Invalid pax data");
4115 }
4116 // eol points to the space between the count and the key
4117 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4118 int key = eol + 1; // start of key=value
4119 eol = offset + linelen - 1; // trailing LF
4120 int value;
4121 for (value = key+1; data[value] != '=' && value <= eol; value++);
4122 if (value > eol) {
4123 throw new IOException("Invalid pax declaration");
4124 }
4125
4126 // pax requires that key/value strings be in UTF-8
4127 String keyStr = new String(data, key, value-key, "UTF-8");
4128 // -1 to strip the trailing LF
4129 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4130
4131 if ("path".equals(keyStr)) {
4132 info.path = valStr;
4133 } else if ("size".equals(keyStr)) {
4134 info.size = Long.parseLong(valStr);
4135 } else {
4136 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4137 }
4138
4139 offset += linelen;
4140 } while (offset < contentSize);
4141
4142 return true;
4143 }
4144
4145 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4146 throws IOException {
4147 long value = 0;
4148 final int end = offset + maxChars;
4149 for (int i = offset; i < end; i++) {
4150 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004151 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004152 if (b == 0 || b == ' ') break;
4153 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004154 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004155 }
4156 value = radix * value + (b - '0');
4157 }
4158 return value;
4159 }
4160
4161 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4162 final int end = offset + maxChars;
4163 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004164 // tar string fields terminate early with a NUL
4165 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004166 return new String(data, offset, eos-offset, "US-ASCII");
4167 }
4168
4169 void sendStartRestore() {
4170 if (mObserver != null) {
4171 try {
4172 mObserver.onStartRestore();
4173 } catch (RemoteException e) {
4174 Slog.w(TAG, "full restore observer went away: startRestore");
4175 mObserver = null;
4176 }
4177 }
4178 }
4179
4180 void sendOnRestorePackage(String name) {
4181 if (mObserver != null) {
4182 try {
4183 // TODO: use a more user-friendly name string
4184 mObserver.onRestorePackage(name);
4185 } catch (RemoteException e) {
4186 Slog.w(TAG, "full restore observer went away: restorePackage");
4187 mObserver = null;
4188 }
4189 }
4190 }
4191
4192 void sendEndRestore() {
4193 if (mObserver != null) {
4194 try {
4195 mObserver.onEndRestore();
4196 } catch (RemoteException e) {
4197 Slog.w(TAG, "full restore observer went away: endRestore");
4198 mObserver = null;
4199 }
4200 }
4201 }
4202 }
4203
Christopher Tatedf01dea2009-06-09 20:45:02 -07004204 // ----- Restore handling -----
4205
Christopher Tate78dd4a72009-11-04 11:49:08 -08004206 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4207 // If the target resides on the system partition, we allow it to restore
4208 // data from the like-named package in a restore set even if the signatures
4209 // do not match. (Unlike general applications, those flashed to the system
4210 // partition will be signed with the device's platform certificate, so on
4211 // different phones the same system app will have different signatures.)
4212 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004213 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004214 return true;
4215 }
4216
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004217 // Allow unsigned apps, but not signed on one device and unsigned on the other
4218 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004219 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004220 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004221 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004222 if ((storedSigs == null || storedSigs.length == 0)
4223 && (deviceSigs == null || deviceSigs.length == 0)) {
4224 return true;
4225 }
4226 if (storedSigs == null || deviceSigs == null) {
4227 return false;
4228 }
4229
Christopher Tateabce4e82009-06-18 18:35:32 -07004230 // !!! TODO: this demands that every stored signature match one
4231 // that is present on device, and does not demand the converse.
4232 // Is this this right policy?
4233 int nStored = storedSigs.length;
4234 int nDevice = deviceSigs.length;
4235
4236 for (int i=0; i < nStored; i++) {
4237 boolean match = false;
4238 for (int j=0; j < nDevice; j++) {
4239 if (storedSigs[i].equals(deviceSigs[j])) {
4240 match = true;
4241 break;
4242 }
4243 }
4244 if (!match) {
4245 return false;
4246 }
4247 }
4248 return true;
4249 }
4250
Christopher Tate2982d062011-09-06 20:35:24 -07004251 enum RestoreState {
4252 INITIAL,
4253 DOWNLOAD_DATA,
4254 PM_METADATA,
4255 RUNNING_QUEUE,
4256 FINAL
4257 }
4258
4259 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004260 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004261 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004262 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004263 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004264 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004265 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004266 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004267 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004268 private long mStartRealtime;
4269 private PackageManagerBackupAgent mPmAgent;
4270 private List<PackageInfo> mAgentPackages;
4271 private ArrayList<PackageInfo> mRestorePackages;
4272 private RestoreState mCurrentState;
4273 private int mCount;
4274 private boolean mFinished;
4275 private int mStatus;
4276 private File mBackupDataName;
4277 private File mNewStateName;
4278 private File mSavedStateName;
4279 private ParcelFileDescriptor mBackupData;
4280 private ParcelFileDescriptor mNewState;
4281 private PackageInfo mCurrentPackage;
4282
Christopher Tatedf01dea2009-06-09 20:45:02 -07004283
Christopher Tate5cbbf562009-06-22 16:44:51 -07004284 class RestoreRequest {
4285 public PackageInfo app;
4286 public int storedAppVersion;
4287
4288 RestoreRequest(PackageInfo _app, int _version) {
4289 app = _app;
4290 storedAppVersion = _version;
4291 }
4292 }
4293
Christopher Tate44a27902010-01-27 17:15:49 -08004294 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004295 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004296 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004297 mCurrentState = RestoreState.INITIAL;
4298 mFinished = false;
4299 mPmAgent = null;
4300
Christopher Tatedf01dea2009-06-09 20:45:02 -07004301 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004302 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004303 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004304 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004305 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004306 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004307
Christopher Tate284f1bb2011-07-07 14:31:18 -07004308 if (filterSet != null) {
4309 mFilterSet = new HashSet<String>();
4310 for (String pkg : filterSet) {
4311 mFilterSet.add(pkg);
4312 }
4313 } else {
4314 mFilterSet = null;
4315 }
4316
Christopher Tate5cb400b2009-06-25 16:03:14 -07004317 try {
4318 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4319 } catch (RemoteException e) {
4320 // can't happen; the transport is local
4321 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004322 }
4323
Christopher Tate2982d062011-09-06 20:35:24 -07004324 // Execute one tick of whatever state machine the task implements
4325 @Override
4326 public void execute() {
4327 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4328 switch (mCurrentState) {
4329 case INITIAL:
4330 beginRestore();
4331 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004332
Christopher Tate2982d062011-09-06 20:35:24 -07004333 case DOWNLOAD_DATA:
4334 downloadRestoreData();
4335 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004336
Christopher Tate2982d062011-09-06 20:35:24 -07004337 case PM_METADATA:
4338 restorePmMetadata();
4339 break;
4340
4341 case RUNNING_QUEUE:
4342 restoreNextAgent();
4343 break;
4344
4345 case FINAL:
4346 if (!mFinished) finalizeRestore();
4347 else {
4348 Slog.e(TAG, "Duplicate finish");
4349 }
4350 mFinished = true;
4351 break;
4352 }
4353 }
4354
4355 // Initialize and set up for the PM metadata restore, which comes first
4356 void beginRestore() {
4357 // Don't account time doing the restore as inactivity of the app
4358 // that has opened a restore session.
4359 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4360
4361 // Assume error until we successfully init everything
4362 mStatus = BackupConstants.TRANSPORT_ERROR;
4363
Christopher Tatedf01dea2009-06-09 20:45:02 -07004364 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004365 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004366 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004367
Dan Egnorefe52642009-06-24 00:16:33 -07004368 // Get the list of all packages which have backup enabled.
4369 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004370 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004371 PackageInfo omPackage = new PackageInfo();
4372 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004373 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004374
Christopher Tate2982d062011-09-06 20:35:24 -07004375 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004376 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004377 // if there's a filter set, strip out anything that isn't
4378 // present before proceeding
4379 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004380 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4381 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004382 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004383 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004384 }
4385 }
Christopher Tate2982d062011-09-06 20:35:24 -07004386 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004387 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004388 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004389 Slog.i(TAG, " " + p);
4390 }
4391 }
4392 }
Christopher Tate2982d062011-09-06 20:35:24 -07004393 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004394 } else {
4395 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004396 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004397 }
Dan Egnorefe52642009-06-24 00:16:33 -07004398
Christopher Tate7d562ec2009-06-25 18:03:43 -07004399 // let the observer know that we're running
4400 if (mObserver != null) {
4401 try {
4402 // !!! TODO: get an actual count from the transport after
4403 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004404 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004405 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004406 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004407 mObserver = null;
4408 }
4409 }
Christopher Tate2982d062011-09-06 20:35:24 -07004410 } catch (RemoteException e) {
4411 // Something has gone catastrophically wrong with the transport
4412 Slog.e(TAG, "Error communicating with transport for restore");
4413 executeNextState(RestoreState.FINAL);
4414 return;
4415 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004416
Christopher Tate2982d062011-09-06 20:35:24 -07004417 mStatus = BackupConstants.TRANSPORT_OK;
4418 executeNextState(RestoreState.DOWNLOAD_DATA);
4419 }
4420
4421 void downloadRestoreData() {
4422 // Note that the download phase can be very time consuming, but we're executing
4423 // it inline here on the looper. This is "okay" because it is not calling out to
4424 // third party code; the transport is "trusted," and so we assume it is being a
4425 // good citizen and timing out etc when appropriate.
4426 //
4427 // TODO: when appropriate, move the download off the looper and rearrange the
4428 // error handling around that.
4429 try {
4430 mStatus = mTransport.startRestore(mToken,
4431 mRestorePackages.toArray(new PackageInfo[0]));
4432 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004433 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004434 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004435 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004436 return;
4437 }
Christopher Tate2982d062011-09-06 20:35:24 -07004438 } catch (RemoteException e) {
4439 Slog.e(TAG, "Error communicating with transport for restore");
4440 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4441 mStatus = BackupConstants.TRANSPORT_ERROR;
4442 executeNextState(RestoreState.FINAL);
4443 return;
4444 }
Dan Egnorefe52642009-06-24 00:16:33 -07004445
Christopher Tate2982d062011-09-06 20:35:24 -07004446 // Successful download of the data to be parceled out to the apps, so off we go.
4447 executeNextState(RestoreState.PM_METADATA);
4448 }
4449
4450 void restorePmMetadata() {
4451 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004452 String packageName = mTransport.nextRestorePackage();
4453 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004454 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004455 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004456 mStatus = BackupConstants.TRANSPORT_ERROR;
4457 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004458 return;
4459 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004460 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004461 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004462 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004463 mStatus = BackupConstants.TRANSPORT_OK;
4464 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004465 return;
4466 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004467 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004468 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004469 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004470 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004471 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004472 return;
4473 }
4474
4475 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004476 PackageInfo omPackage = new PackageInfo();
4477 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4478 mPmAgent = new PackageManagerBackupAgent(
4479 mPackageManager, mAgentPackages);
4480 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004481 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004482 // The PM agent called operationComplete() already, because our invocation
4483 // of it is process-local and therefore synchronous. That means that a
4484 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4485 // proceed with running the queue do we remove that pending message and
4486 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004487
Christopher Tate8c032472009-07-02 14:28:47 -07004488 // Verify that the backup set includes metadata. If not, we can't do
4489 // signature/version verification etc, so we simply do not proceed with
4490 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004491 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004492 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004493 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004494 "Package manager restore metadata missing");
4495 mStatus = BackupConstants.TRANSPORT_ERROR;
4496 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4497 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004498 return;
4499 }
Christopher Tate2982d062011-09-06 20:35:24 -07004500 } catch (RemoteException e) {
4501 Slog.e(TAG, "Error communicating with transport for restore");
4502 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4503 mStatus = BackupConstants.TRANSPORT_ERROR;
4504 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4505 executeNextState(RestoreState.FINAL);
4506 return;
4507 }
Christopher Tate8c032472009-07-02 14:28:47 -07004508
Christopher Tate2982d062011-09-06 20:35:24 -07004509 // Metadata is intact, so we can now run the restore queue. If we get here,
4510 // we have already enqueued the necessary next-step message on the looper.
4511 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004512
Christopher Tate2982d062011-09-06 20:35:24 -07004513 void restoreNextAgent() {
4514 try {
4515 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004516
Christopher Tate2982d062011-09-06 20:35:24 -07004517 if (packageName == null) {
4518 Slog.e(TAG, "Error getting next restore package");
4519 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4520 executeNextState(RestoreState.FINAL);
4521 return;
4522 } else if (packageName.equals("")) {
4523 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4524 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4525 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4526 executeNextState(RestoreState.FINAL);
4527 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004528 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004529
4530 if (mObserver != null) {
4531 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004532 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004533 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004534 Slog.d(TAG, "Restore observer died in onUpdate");
4535 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004536 }
4537 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004538
Christopher Tate2982d062011-09-06 20:35:24 -07004539 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4540 if (metaInfo == null) {
4541 Slog.e(TAG, "Missing metadata for " + packageName);
4542 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4543 "Package metadata missing");
4544 executeNextState(RestoreState.RUNNING_QUEUE);
4545 return;
Christopher Tate84725812010-02-04 15:52:40 -08004546 }
4547
Christopher Tate2982d062011-09-06 20:35:24 -07004548 PackageInfo packageInfo;
4549 try {
4550 int flags = PackageManager.GET_SIGNATURES;
4551 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4552 } catch (NameNotFoundException e) {
4553 Slog.e(TAG, "Invalid package restoring data", e);
4554 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4555 "Package missing on device");
4556 executeNextState(RestoreState.RUNNING_QUEUE);
4557 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004558 }
4559
Christopher Tatee7287a02012-09-07 18:32:12 -07004560 if (packageInfo.applicationInfo.backupAgentName == null
4561 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4562 if (DEBUG) {
4563 Slog.i(TAG, "Data exists for package " + packageName
4564 + " but app has no agent; skipping");
4565 }
4566 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4567 "Package has no agent");
4568 executeNextState(RestoreState.RUNNING_QUEUE);
4569 return;
4570 }
4571
Christopher Tate2982d062011-09-06 20:35:24 -07004572 if (metaInfo.versionCode > packageInfo.versionCode) {
4573 // Data is from a "newer" version of the app than we have currently
4574 // installed. If the app has not declared that it is prepared to
4575 // handle this case, we do not attempt the restore.
4576 if ((packageInfo.applicationInfo.flags
4577 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4578 String message = "Version " + metaInfo.versionCode
4579 + " > installed version " + packageInfo.versionCode;
4580 Slog.w(TAG, "Package " + packageName + ": " + message);
4581 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4582 packageName, message);
4583 executeNextState(RestoreState.RUNNING_QUEUE);
4584 return;
4585 } else {
4586 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4587 + " > installed " + packageInfo.versionCode
4588 + " but restoreAnyVersion");
4589 }
4590 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004591
Christopher Tate2982d062011-09-06 20:35:24 -07004592 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4593 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4594 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4595 "Signature mismatch");
4596 executeNextState(RestoreState.RUNNING_QUEUE);
4597 return;
4598 }
4599
4600 if (DEBUG) Slog.v(TAG, "Package " + packageName
4601 + " restore version [" + metaInfo.versionCode
4602 + "] is compatible with installed version ["
4603 + packageInfo.versionCode + "]");
4604
4605 // Then set up and bind the agent
4606 IBackupAgent agent = bindToAgentSynchronous(
4607 packageInfo.applicationInfo,
4608 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4609 if (agent == null) {
4610 Slog.w(TAG, "Can't find backup agent for " + packageName);
4611 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4612 "Restore agent missing");
4613 executeNextState(RestoreState.RUNNING_QUEUE);
4614 return;
4615 }
4616
4617 // And then finally start the restore on this agent
4618 try {
4619 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4620 ++mCount;
4621 } catch (Exception e) {
4622 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4623 agentErrorCleanup();
4624 executeNextState(RestoreState.RUNNING_QUEUE);
4625 }
4626 } catch (RemoteException e) {
4627 Slog.e(TAG, "Unable to fetch restore data from transport");
4628 mStatus = BackupConstants.TRANSPORT_ERROR;
4629 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004630 }
4631 }
4632
Christopher Tate2982d062011-09-06 20:35:24 -07004633 void finalizeRestore() {
4634 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4635
4636 try {
4637 mTransport.finishRestore();
4638 } catch (RemoteException e) {
4639 Slog.e(TAG, "Error finishing restore", e);
4640 }
4641
4642 if (mObserver != null) {
4643 try {
4644 mObserver.restoreFinished(mStatus);
4645 } catch (RemoteException e) {
4646 Slog.d(TAG, "Restore observer died at restoreFinished");
4647 }
4648 }
4649
4650 // If this was a restoreAll operation, record that this was our
4651 // ancestral dataset, as well as the set of apps that are possibly
4652 // restoreable from the dataset
4653 if (mTargetPackage == null && mPmAgent != null) {
4654 mAncestralPackages = mPmAgent.getRestoredPackages();
4655 mAncestralToken = mToken;
4656 writeRestoreTokens();
4657 }
4658
4659 // We must under all circumstances tell the Package Manager to
4660 // proceed with install notifications if it's waiting for us.
4661 if (mPmToken > 0) {
4662 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4663 try {
4664 mPackageManagerBinder.finishPackageInstall(mPmToken);
4665 } catch (RemoteException e) { /* can't happen */ }
4666 }
4667
4668 // Furthermore we need to reset the session timeout clock
4669 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4670 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4671 TIMEOUT_RESTORE_INTERVAL);
4672
4673 // done; we can finally release the wakelock
4674 Slog.i(TAG, "Restore complete.");
4675 mWakelock.release();
4676 }
4677
4678 // Call asynchronously into the app, passing it the restore data. The next step
4679 // after this is always a callback, either operationComplete() or handleTimeout().
4680 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004681 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004682 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004683 final String packageName = app.packageName;
4684
Christopher Tate2982d062011-09-06 20:35:24 -07004685 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004686
Christopher Tatec7b31e32009-06-10 15:49:30 -07004687 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004688 mBackupDataName = new File(mDataDir, packageName + ".restore");
4689 mNewStateName = new File(mStateDir, packageName + ".new");
4690 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004691
Christopher Tate4a627c72011-04-01 14:43:32 -07004692 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004693 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004694 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004695 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004696 ParcelFileDescriptor.MODE_READ_WRITE |
4697 ParcelFileDescriptor.MODE_CREATE |
4698 ParcelFileDescriptor.MODE_TRUNCATE);
4699
Christopher Tate2982d062011-09-06 20:35:24 -07004700 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004701 // Transport-level failure, so we wind everything up and
4702 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004703 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004704 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004705 mBackupData.close();
4706 mBackupDataName.delete();
4707 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004708 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004709 }
4710
4711 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004712 mBackupData.close();
4713 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004714 ParcelFileDescriptor.MODE_READ_ONLY);
4715
Christopher Tate2982d062011-09-06 20:35:24 -07004716 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004717 ParcelFileDescriptor.MODE_READ_WRITE |
4718 ParcelFileDescriptor.MODE_CREATE |
4719 ParcelFileDescriptor.MODE_TRUNCATE);
4720
Christopher Tate44a27902010-01-27 17:15:49 -08004721 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004722 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4723 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004724 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004725 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004726 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004727 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004728
Christopher Tate2982d062011-09-06 20:35:24 -07004729 // After a restore failure we go back to running the queue. If there
4730 // are no more packages to be restored that will be handled by the
4731 // next step.
4732 executeNextState(RestoreState.RUNNING_QUEUE);
4733 }
4734 }
Chris Tate249345b2010-10-29 12:57:04 -07004735
Christopher Tate2982d062011-09-06 20:35:24 -07004736 void agentErrorCleanup() {
4737 // If the agent fails restore, it might have put the app's data
4738 // into an incoherent state. For consistency we wipe its data
4739 // again in this case before continuing with normal teardown
4740 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4741 agentCleanup();
4742 }
4743
4744 void agentCleanup() {
4745 mBackupDataName.delete();
4746 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4747 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4748 mBackupData = mNewState = null;
4749
4750 // if everything went okay, remember the recorded state now
4751 //
4752 // !!! TODO: the restored data should be migrated on the server
4753 // side into the current dataset. In that case the new state file
4754 // we just created would reflect the data already extant in the
4755 // backend, so there'd be nothing more to do. Until that happens,
4756 // however, we need to make sure that we record the data to the
4757 // current backend dataset. (Yes, this means shipping the data over
4758 // the wire in both directions. That's bad, but consistency comes
4759 // first, then efficiency.) Once we introduce server-side data
4760 // migration to the newly-restored device's dataset, we will change
4761 // the following from a discard of the newly-written state to the
4762 // "correct" operation of renaming into the canonical state blob.
4763 mNewStateName.delete(); // TODO: remove; see above comment
4764 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4765
4766 // If this wasn't the PM pseudopackage, tear down the agent side
4767 if (mCurrentPackage.applicationInfo != null) {
4768 // unbind and tidy up even on timeout or failure
4769 try {
4770 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4771
4772 // The agent was probably running with a stub Application object,
4773 // which isn't a valid run mode for the main app logic. Shut
4774 // down the app so that next time it's launched, it gets the
4775 // usual full initialization. Note that this is only done for
4776 // full-system restores: when a single app has requested a restore,
4777 // it is explicitly not killed following that operation.
4778 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4779 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4780 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4781 + mCurrentPackage.applicationInfo.processName);
4782 mActivityManager.killApplicationProcess(
4783 mCurrentPackage.applicationInfo.processName,
4784 mCurrentPackage.applicationInfo.uid);
4785 }
4786 } catch (RemoteException e) {
4787 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004788 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004789 }
Christopher Tate2982d062011-09-06 20:35:24 -07004790
4791 // The caller is responsible for reestablishing the state machine; our
4792 // responsibility here is to clear the decks for whatever comes next.
4793 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4794 synchronized (mCurrentOpLock) {
4795 mCurrentOperations.clear();
4796 }
4797 }
4798
4799 // A call to agent.doRestore() has been positively acknowledged as complete
4800 @Override
4801 public void operationComplete() {
4802 int size = (int) mBackupDataName.length();
4803 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4804 // Just go back to running the restore queue
4805 agentCleanup();
4806
4807 executeNextState(RestoreState.RUNNING_QUEUE);
4808 }
4809
4810 // A call to agent.doRestore() has timed out
4811 @Override
4812 public void handleTimeout() {
4813 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4814 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4815 mCurrentPackage.packageName, "restore timeout");
4816 // Handle like an agent that threw on invocation: wipe it and go on to the next
4817 agentErrorCleanup();
4818 executeNextState(RestoreState.RUNNING_QUEUE);
4819 }
4820
4821 void executeNextState(RestoreState nextState) {
4822 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4823 + this + " nextState=" + nextState);
4824 mCurrentState = nextState;
4825 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4826 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004827 }
4828 }
4829
Christopher Tate44a27902010-01-27 17:15:49 -08004830 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004831 IBackupTransport mTransport;
4832 PackageInfo mPackage;
4833
Christopher Tate44a27902010-01-27 17:15:49 -08004834 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004835 mTransport = transport;
4836 mPackage = packageInfo;
4837 }
4838
Christopher Tateee0e78a2009-07-02 11:17:03 -07004839 public void run() {
4840 try {
4841 // Clear the on-device backup state to ensure a full backup next time
4842 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4843 File stateFile = new File(stateDir, mPackage.packageName);
4844 stateFile.delete();
4845
4846 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004847 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004848 mTransport.clearBackupData(mPackage);
4849 } catch (RemoteException e) {
4850 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004851 } catch (Exception e) {
4852 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004853 } finally {
4854 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004855 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004856 mTransport.finishBackup();
4857 } catch (RemoteException e) {
4858 // can't happen; the transport is local
4859 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004860
4861 // Last but not least, release the cpu
4862 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004863 }
4864 }
4865 }
4866
Christopher Tate44a27902010-01-27 17:15:49 -08004867 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004868 HashSet<String> mQueue;
4869
Christopher Tate44a27902010-01-27 17:15:49 -08004870 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004871 mQueue = transportNames;
4872 }
4873
Christopher Tate4cc86e12009-09-21 19:36:51 -07004874 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004875 try {
4876 for (String transportName : mQueue) {
4877 IBackupTransport transport = getTransport(transportName);
4878 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004879 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004880 continue;
4881 }
4882
Joe Onorato8a9b2202010-02-26 18:56:32 -08004883 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004884 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004885 long startRealtime = SystemClock.elapsedRealtime();
4886 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004887
Christopher Tate4cc86e12009-09-21 19:36:51 -07004888 if (status == BackupConstants.TRANSPORT_OK) {
4889 status = transport.finishBackup();
4890 }
4891
4892 // Okay, the wipe really happened. Clean up our local bookkeeping.
4893 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004894 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004895 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004896 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004897 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004898 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004899 synchronized (mQueueLock) {
4900 recordInitPendingLocked(false, transportName);
4901 }
Dan Egnor726247c2009-09-29 19:12:31 -07004902 } else {
4903 // If this didn't work, requeue this one and try again
4904 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004905 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004906 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004907 synchronized (mQueueLock) {
4908 recordInitPendingLocked(true, transportName);
4909 }
4910 // do this via another alarm to make sure of the wakelock states
4911 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004912 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004913 + transportName + " resched in " + delay);
4914 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4915 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004916 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004917 }
4918 } catch (RemoteException e) {
4919 // can't happen; the transports are local
4920 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004921 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004922 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004923 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004924 mWakelock.release();
4925 }
4926 }
4927 }
4928
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004929 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004930 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004931 dataChangedImpl(packageName, targets);
4932 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004933
Christopher Tatea3d55342012-03-27 13:16:18 -07004934 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004935 // Record that we need a backup pass for the caller. Since multiple callers
4936 // may share a uid, we need to note all candidates within that uid and schedule
4937 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004938 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004939
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004940 if (targets == null) {
4941 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4942 + " uid=" + Binder.getCallingUid());
4943 return;
4944 }
4945
4946 synchronized (mQueueLock) {
4947 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004948 if (targets.contains(packageName)) {
4949 // Add the caller to the set of pending backups. If there is
4950 // one already there, then overwrite it, but no harm done.
4951 BackupRequest req = new BackupRequest(packageName);
4952 if (mPendingBackups.put(packageName, req) == null) {
4953 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004954
Christopher Tatea3d55342012-03-27 13:16:18 -07004955 // Journal this request in case of crash. The put()
4956 // operation returned null when this package was not already
4957 // in the set; we want to avoid touching the disk redundantly.
4958 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004959
Christopher Tatea3d55342012-03-27 13:16:18 -07004960 if (MORE_DEBUG) {
4961 int numKeys = mPendingBackups.size();
4962 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4963 for (BackupRequest b : mPendingBackups.values()) {
4964 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004965 }
4966 }
4967 }
4968 }
4969 }
4970 }
4971
4972 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004973 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004974 // If the caller does not hold the BACKUP permission, it can only request a
4975 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004976 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004977 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004978 synchronized (mBackupParticipants) {
4979 return mBackupParticipants.get(Binder.getCallingUid());
4980 }
4981 }
4982
4983 // a caller with full permission can ask to back up any participating app
4984 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004985 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004986 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004987 int N = mBackupParticipants.size();
4988 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004989 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004990 if (s != null) {
4991 targets.addAll(s);
4992 }
4993 }
4994 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004995 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004996 }
Christopher Tate46758122009-05-06 11:22:00 -07004997
Christopher Tatecde87f42009-06-12 12:55:53 -07004998 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004999 RandomAccessFile out = null;
5000 try {
5001 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5002 out = new RandomAccessFile(mJournal, "rws");
5003 out.seek(out.length());
5004 out.writeUTF(str);
5005 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005006 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005007 mJournal = null;
5008 } finally {
5009 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07005010 }
5011 }
5012
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005013 // ----- IBackupManager binder interface -----
5014
5015 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005016 final int callingUserHandle = UserHandle.getCallingUserId();
5017 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005018 // App is running under a non-owner user profile. For now, we do not back
5019 // up data from secondary user profiles.
5020 // TODO: backups for all user profiles.
5021 if (MORE_DEBUG) {
5022 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5023 + callingUserHandle);
5024 }
5025 return;
5026 }
5027
Christopher Tatea3d55342012-03-27 13:16:18 -07005028 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005029 if (targets == null) {
5030 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5031 + " uid=" + Binder.getCallingUid());
5032 return;
5033 }
5034
5035 mBackupHandler.post(new Runnable() {
5036 public void run() {
5037 dataChangedImpl(packageName, targets);
5038 }
5039 });
5040 }
5041
Christopher Tateee0e78a2009-07-02 11:17:03 -07005042 // Clear the given package's backup data from the current transport
5043 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005044 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005045 PackageInfo info;
5046 try {
5047 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5048 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005049 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07005050 return;
5051 }
5052
5053 // If the caller does not hold the BACKUP permission, it can only request a
5054 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07005055 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005056 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07005057 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5058 apps = mBackupParticipants.get(Binder.getCallingUid());
5059 } else {
5060 // a caller with full permission can ask to back up any participating app
5061 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08005062 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07005063 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07005064 int N = mBackupParticipants.size();
5065 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005066 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005067 if (s != null) {
5068 apps.addAll(s);
5069 }
5070 }
5071 }
5072
Christopher Tatea3d55342012-03-27 13:16:18 -07005073 // Is the given app an available participant?
5074 if (apps.contains(packageName)) {
5075 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5076 // found it; fire off the clear request
5077 synchronized (mQueueLock) {
5078 long oldId = Binder.clearCallingIdentity();
5079 mWakelock.acquire();
5080 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5081 new ClearParams(getTransport(mCurrentTransport), info));
5082 mBackupHandler.sendMessage(msg);
5083 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005084 }
5085 }
5086 }
5087
Christopher Tateace7f092009-06-15 18:07:25 -07005088 // Run a backup pass immediately for any applications that have declared
5089 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07005090 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04005091 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07005092
Joe Onorato8a9b2202010-02-26 18:56:32 -08005093 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07005094 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005095 // Because the alarms we are using can jitter, and we want an *immediate*
5096 // backup pass to happen, we restart the timer beginning with "next time,"
5097 // then manually fire the backup trigger intent ourselves.
5098 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07005099 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07005100 mRunBackupIntent.send();
5101 } catch (PendingIntent.CanceledException e) {
5102 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08005103 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07005104 }
Christopher Tate46758122009-05-06 11:22:00 -07005105 }
5106 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005107
Christopher Tated2c0cd42011-09-15 15:51:29 -07005108 boolean deviceIsProvisioned() {
5109 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07005110 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005111 }
5112
Christopher Tate4a627c72011-04-01 14:43:32 -07005113 // Run a *full* backup pass for the given package, writing the resulting data stream
5114 // to the supplied file descriptor. This method is synchronous and does not return
5115 // to the caller until the backup has been completed.
Christopher Tate294b5122013-02-19 14:08:59 -08005116 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5117 boolean includeObbs, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005118 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005119 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5120
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005121 final int callingUserHandle = UserHandle.getCallingUserId();
5122 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005123 throw new IllegalStateException("Backup supported only for the device owner");
5124 }
5125
Christopher Tate4a627c72011-04-01 14:43:32 -07005126 // Validate
5127 if (!doAllApps) {
5128 if (!includeShared) {
5129 // If we're backing up shared data (sdcard or equivalent), then we can run
5130 // without any supplied app names. Otherwise, we'd be doing no work, so
5131 // report the error.
5132 if (pkgList == null || pkgList.length == 0) {
5133 throw new IllegalArgumentException(
5134 "Backup requested but neither shared nor any apps named");
5135 }
5136 }
5137 }
5138
Christopher Tate4a627c72011-04-01 14:43:32 -07005139 long oldId = Binder.clearCallingIdentity();
5140 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005141 // Doesn't make sense to do a full backup prior to setup
5142 if (!deviceIsProvisioned()) {
5143 Slog.i(TAG, "Full backup not supported before setup");
5144 return;
5145 }
5146
5147 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
Christopher Tate294b5122013-02-19 14:08:59 -08005148 + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
Christopher Tated2c0cd42011-09-15 15:51:29 -07005149 + " pkgs=" + pkgList);
5150 Slog.i(TAG, "Beginning full backup...");
5151
Christopher Tate294b5122013-02-19 14:08:59 -08005152 FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5153 includeShared, doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005154 final int token = generateToken();
5155 synchronized (mFullConfirmations) {
5156 mFullConfirmations.put(token, params);
5157 }
5158
Christopher Tate75a99702011-05-18 16:28:19 -07005159 // start up the confirmation UI
5160 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5161 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5162 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005163 mFullConfirmations.delete(token);
5164 return;
5165 }
Christopher Tate75a99702011-05-18 16:28:19 -07005166
5167 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005168 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5169
5170 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005171 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005172
5173 // wait for the backup to be performed
5174 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5175 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005176 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005177 try {
5178 fd.close();
5179 } catch (IOException e) {
5180 // just eat it
5181 }
Christopher Tate75a99702011-05-18 16:28:19 -07005182 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005183 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005184 }
Christopher Tate75a99702011-05-18 16:28:19 -07005185 }
5186
5187 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005188 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005189
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005190 final int callingUserHandle = UserHandle.getCallingUserId();
5191 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005192 throw new IllegalStateException("Restore supported only for the device owner");
5193 }
5194
Christopher Tate75a99702011-05-18 16:28:19 -07005195 long oldId = Binder.clearCallingIdentity();
5196
5197 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005198 // Check whether the device has been provisioned -- we don't handle
5199 // full restores prior to completing the setup process.
5200 if (!deviceIsProvisioned()) {
5201 Slog.i(TAG, "Full restore not permitted before setup");
5202 return;
5203 }
5204
5205 Slog.i(TAG, "Beginning full restore...");
5206
Christopher Tate75a99702011-05-18 16:28:19 -07005207 FullRestoreParams params = new FullRestoreParams(fd);
5208 final int token = generateToken();
5209 synchronized (mFullConfirmations) {
5210 mFullConfirmations.put(token, params);
5211 }
5212
5213 // start up the confirmation UI
5214 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5215 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5216 Slog.e(TAG, "Unable to launch full restore confirmation");
5217 mFullConfirmations.delete(token);
5218 return;
5219 }
5220
5221 // make sure the screen is lit for the user interaction
5222 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5223
5224 // start the confirmation countdown
5225 startConfirmationTimeout(token, params);
5226
5227 // wait for the restore to be performed
5228 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5229 waitForCompletion(params);
5230 } finally {
5231 try {
5232 fd.close();
5233 } catch (IOException e) {
5234 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5235 }
5236 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005237 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005238 }
5239 }
5240
5241 boolean startConfirmationUi(int token, String action) {
5242 try {
5243 Intent confIntent = new Intent(action);
5244 confIntent.setClassName("com.android.backupconfirm",
5245 "com.android.backupconfirm.BackupRestoreConfirmation");
5246 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5247 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5248 mContext.startActivity(confIntent);
5249 } catch (ActivityNotFoundException e) {
5250 return false;
5251 }
5252 return true;
5253 }
5254
5255 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005256 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005257 + TIMEOUT_FULL_CONFIRMATION + " millis");
5258 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5259 token, 0, params);
5260 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005261 }
5262
5263 void waitForCompletion(FullParams params) {
5264 synchronized (params.latch) {
5265 while (params.latch.get() == false) {
5266 try {
5267 params.latch.wait();
5268 } catch (InterruptedException e) { /* never interrupted */ }
5269 }
5270 }
5271 }
5272
5273 void signalFullBackupRestoreCompletion(FullParams params) {
5274 synchronized (params.latch) {
5275 params.latch.set(true);
5276 params.latch.notifyAll();
5277 }
5278 }
5279
5280 // Confirm that the previously-requested full backup/restore operation can proceed. This
5281 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005282 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005283 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005284 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005285 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5286 + " allow=" + allow);
5287
5288 // TODO: possibly require not just this signature-only permission, but even
5289 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005290 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005291
5292 long oldId = Binder.clearCallingIdentity();
5293 try {
5294
5295 FullParams params;
5296 synchronized (mFullConfirmations) {
5297 params = mFullConfirmations.get(token);
5298 if (params != null) {
5299 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5300 mFullConfirmations.delete(token);
5301
5302 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005303 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005304 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005305 : MSG_RUN_FULL_RESTORE;
5306
Christopher Tate728a1c42011-07-28 18:03:03 -07005307 params.observer = observer;
5308 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005309
5310 boolean isEncrypted;
5311 try {
5312 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5313 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5314 } catch (RemoteException e) {
5315 // couldn't contact the mount service; fail "safe" and assume encryption
5316 Slog.e(TAG, "Unable to contact mount service!");
5317 isEncrypted = true;
5318 }
5319 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005320
Christopher Tate75a99702011-05-18 16:28:19 -07005321 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005322 mWakelock.acquire();
5323 Message msg = mBackupHandler.obtainMessage(verb, params);
5324 mBackupHandler.sendMessage(msg);
5325 } else {
5326 Slog.w(TAG, "User rejected full backup/restore operation");
5327 // indicate completion without having actually transferred any data
5328 signalFullBackupRestoreCompletion(params);
5329 }
5330 } else {
5331 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5332 }
5333 }
5334 } finally {
5335 Binder.restoreCallingIdentity(oldId);
5336 }
5337 }
5338
Christopher Tate8031a3d2009-07-06 16:36:05 -07005339 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005340 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005341 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005342 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005343
Joe Onorato8a9b2202010-02-26 18:56:32 -08005344 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005345
Christopher Tate6ef58a12009-06-29 14:56:28 -07005346 boolean wasEnabled = mEnabled;
5347 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005348 Settings.Secure.putInt(mContext.getContentResolver(),
5349 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005350 mEnabled = enable;
5351 }
5352
Christopher Tate49401dd2009-07-01 12:34:29 -07005353 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005354 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005355 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005356 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005357 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005358 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005359 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005360
Christopher Tateb6787f22009-07-02 17:40:45 -07005361 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005362
5363 // This also constitutes an opt-out, so we wipe any data for
5364 // this device from the backend. We start that process with
5365 // an alarm in order to guarantee wakelock states.
5366 if (wasEnabled && mProvisioned) {
5367 // NOTE: we currently flush every registered transport, not just
5368 // the currently-active one.
5369 HashSet<String> allTransports;
5370 synchronized (mTransports) {
5371 allTransports = new HashSet<String>(mTransports.keySet());
5372 }
5373 // build the set of transports for which we are posting an init
5374 for (String transport : allTransports) {
5375 recordInitPendingLocked(true, transport);
5376 }
5377 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5378 mRunInitIntent);
5379 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005380 }
5381 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005382 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005383
Christopher Tatecce9da52010-02-03 15:11:15 -08005384 // Enable/disable automatic restore of app data at install time
5385 public void setAutoRestore(boolean doAutoRestore) {
5386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005387 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005388
Joe Onorato8a9b2202010-02-26 18:56:32 -08005389 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005390
5391 synchronized (this) {
5392 Settings.Secure.putInt(mContext.getContentResolver(),
5393 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5394 mAutoRestore = doAutoRestore;
5395 }
5396 }
5397
Christopher Tate8031a3d2009-07-06 16:36:05 -07005398 // Mark the backup service as having been provisioned
5399 public void setBackupProvisioned(boolean available) {
5400 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5401 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005402 /*
5403 * This is now a no-op; provisioning is simply the device's own setup state.
5404 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005405 }
5406
5407 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005408 // We used to use setInexactRepeating(), but that may be linked to
5409 // backups running at :00 more often than not, creating load spikes.
5410 // Schedule at an exact time for now, and also add a bit of "fuzz".
5411
5412 Random random = new Random();
5413 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5414 random.nextInt(FUZZ_MILLIS);
5415 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5416 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005417 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005418 }
5419
Christopher Tate6ef58a12009-06-29 14:56:28 -07005420 // Report whether the backup mechanism is currently enabled
5421 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005423 return mEnabled; // no need to synchronize just to read it
5424 }
5425
Christopher Tate91717492009-06-26 21:07:13 -07005426 // Report the name of the currently active transport
5427 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005428 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005429 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005430 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005431 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005432 }
5433
Christopher Tate91717492009-06-26 21:07:13 -07005434 // Report all known, available backup transports
5435 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005436 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005437
Christopher Tate91717492009-06-26 21:07:13 -07005438 String[] list = null;
5439 ArrayList<String> known = new ArrayList<String>();
5440 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5441 if (entry.getValue() != null) {
5442 known.add(entry.getKey());
5443 }
5444 }
5445
5446 if (known.size() > 0) {
5447 list = new String[known.size()];
5448 known.toArray(list);
5449 }
5450 return list;
5451 }
5452
5453 // Select which transport to use for the next backup operation. If the given
5454 // name is not one of the available transports, no action is taken and the method
5455 // returns null.
5456 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005458
5459 synchronized (mTransports) {
5460 String prevTransport = null;
5461 if (mTransports.get(transport) != null) {
5462 prevTransport = mCurrentTransport;
5463 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005464 Settings.Secure.putString(mContext.getContentResolver(),
5465 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005466 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005467 + " returning " + prevTransport);
5468 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005469 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005470 }
5471 return prevTransport;
5472 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005473 }
5474
Christopher Tatef5e1c292010-12-08 18:40:26 -08005475 // Supply the configuration Intent for the given transport. If the name is not one
5476 // of the available transports, or if the transport does not supply any configuration
5477 // UI, the method returns null.
5478 public Intent getConfigurationIntent(String transportName) {
5479 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5480 "getConfigurationIntent");
5481
5482 synchronized (mTransports) {
5483 final IBackupTransport transport = mTransports.get(transportName);
5484 if (transport != null) {
5485 try {
5486 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005487 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005488 + intent);
5489 return intent;
5490 } catch (RemoteException e) {
5491 /* fall through to return null */
5492 }
5493 }
5494 }
5495
5496 return null;
5497 }
5498
5499 // Supply the configuration summary string for the given transport. If the name is
5500 // not one of the available transports, or if the transport does not supply any
5501 // summary / destination string, the method can return null.
5502 //
5503 // This string is used VERBATIM as the summary text of the relevant Settings item!
5504 public String getDestinationString(String transportName) {
5505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005506 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005507
5508 synchronized (mTransports) {
5509 final IBackupTransport transport = mTransports.get(transportName);
5510 if (transport != null) {
5511 try {
5512 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005513 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005514 return text;
5515 } catch (RemoteException e) {
5516 /* fall through to return null */
5517 }
5518 }
5519 }
5520
5521 return null;
5522 }
5523
Christopher Tate043dadc2009-06-02 16:11:00 -07005524 // Callback: a requested backup agent has been instantiated. This should only
5525 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005526 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005527 synchronized(mAgentConnectLock) {
5528 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005529 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005530 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5531 mConnectedAgent = agent;
5532 mConnecting = false;
5533 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005534 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005535 + " claiming agent connected");
5536 }
5537 mAgentConnectLock.notifyAll();
5538 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005539 }
5540
5541 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5542 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005543 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005544 public void agentDisconnected(String packageName) {
5545 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005546 synchronized(mAgentConnectLock) {
5547 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5548 mConnectedAgent = null;
5549 mConnecting = false;
5550 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005551 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005552 + " claiming agent disconnected");
5553 }
5554 mAgentConnectLock.notifyAll();
5555 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005556 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005557
Christopher Tate1bb69062010-02-19 17:02:12 -08005558 // An application being installed will need a restore pass, then the Package Manager
5559 // will need to be told when the restore is finished.
5560 public void restoreAtInstall(String packageName, int token) {
5561 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005562 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005563 + " attemping install-time restore");
5564 return;
5565 }
5566
5567 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005568 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005569 + " token=" + Integer.toHexString(token)
5570 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005571
Christopher Tatef0872722010-02-25 15:22:48 -08005572 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005573 // okay, we're going to attempt a restore of this package from this restore set.
5574 // The eventual message back into the Package Manager to run the post-install
5575 // steps for 'token' will be issued from the restore handling code.
5576
5577 // We can use a synthetic PackageInfo here because:
5578 // 1. We know it's valid, since the Package Manager supplied the name
5579 // 2. Only the packageName field will be used by the restore code
5580 PackageInfo pkg = new PackageInfo();
5581 pkg.packageName = packageName;
5582
5583 mWakelock.acquire();
5584 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5585 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005586 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005587 mBackupHandler.sendMessage(msg);
5588 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005589 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5590 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005591 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005592 try {
5593 mPackageManagerBinder.finishPackageInstall(token);
5594 } catch (RemoteException e) { /* can't happen */ }
5595 }
5596 }
5597
Christopher Tate8c850b72009-06-07 19:33:20 -07005598 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005599 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5600 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5601 + " transport=" + transport);
5602
5603 boolean needPermission = true;
5604 if (transport == null) {
5605 transport = mCurrentTransport;
5606
5607 if (packageName != null) {
5608 PackageInfo app = null;
5609 try {
5610 app = mPackageManager.getPackageInfo(packageName, 0);
5611 } catch (NameNotFoundException nnf) {
5612 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5613 throw new IllegalArgumentException("Package " + packageName + " not found");
5614 }
5615
5616 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5617 // So: using the current active transport, and the caller has asked
5618 // that its own package will be restored. In this narrow use case
5619 // we do not require the caller to hold the permission.
5620 needPermission = false;
5621 }
5622 }
5623 }
5624
5625 if (needPermission) {
5626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5627 "beginRestoreSession");
5628 } else {
5629 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5630 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005631
5632 synchronized(this) {
5633 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005634 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005635 return null;
5636 }
Chris Tate44ab8452010-11-16 15:10:49 -08005637 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005638 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005639 }
5640 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005641 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005642
Christopher Tate73a3cb32010-12-13 18:27:26 -08005643 void clearRestoreSession(ActiveRestoreSession currentSession) {
5644 synchronized(this) {
5645 if (currentSession != mActiveRestoreSession) {
5646 Slog.e(TAG, "ending non-current restore session");
5647 } else {
5648 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5649 mActiveRestoreSession = null;
5650 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5651 }
5652 }
5653 }
5654
Christopher Tate44a27902010-01-27 17:15:49 -08005655 // Note that a currently-active backup agent has notified us that it has
5656 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005657 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005658 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005659 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5660 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005661 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005662 op = mCurrentOperations.get(token);
5663 if (op != null) {
5664 op.state = OP_ACKNOWLEDGED;
5665 }
Christopher Tate44a27902010-01-27 17:15:49 -08005666 mCurrentOpLock.notifyAll();
5667 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005668
5669 // The completion callback, if any, is invoked on the handler
5670 if (op != null && op.callback != null) {
5671 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5672 mBackupHandler.sendMessage(msg);
5673 }
Christopher Tate44a27902010-01-27 17:15:49 -08005674 }
5675
Christopher Tate9b3905c2009-06-08 15:24:01 -07005676 // ----- Restore session -----
5677
Christopher Tate80202c82010-01-25 19:37:47 -08005678 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005679 private static final String TAG = "RestoreSession";
5680
Chris Tate44ab8452010-11-16 15:10:49 -08005681 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005682 private IBackupTransport mRestoreTransport = null;
5683 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005684 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005685
Chris Tate44ab8452010-11-16 15:10:49 -08005686 ActiveRestoreSession(String packageName, String transport) {
5687 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005688 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005689 }
5690
5691 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005692 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005693 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005694 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005695 if (observer == null) {
5696 throw new IllegalArgumentException("Observer must not be null");
5697 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005698
Christopher Tate73a3cb32010-12-13 18:27:26 -08005699 if (mEnded) {
5700 throw new IllegalStateException("Restore session already ended");
5701 }
5702
Christopher Tate1bb69062010-02-19 17:02:12 -08005703 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005704 try {
Christopher Tate43383042009-07-13 15:17:13 -07005705 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005706 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005707 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005708 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005709 // spin off the transport request to our service thread
5710 mWakelock.acquire();
5711 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5712 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5713 mBackupHandler.sendMessage(msg);
5714 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005715 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005716 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005717 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005718 } finally {
5719 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005720 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005721 }
5722
Christopher Tate84725812010-02-04 15:52:40 -08005723 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5725 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005726
Chris Tate44ab8452010-11-16 15:10:49 -08005727 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005728 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005729
Christopher Tate73a3cb32010-12-13 18:27:26 -08005730 if (mEnded) {
5731 throw new IllegalStateException("Restore session already ended");
5732 }
5733
Dan Egnor0084da52009-07-29 12:57:16 -07005734 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005735 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5736 return -1;
5737 }
5738
5739 if (mPackageName != null) {
5740 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005741 return -1;
5742 }
5743
Christopher Tate21ab6a52009-09-24 18:01:46 -07005744 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005745 for (int i = 0; i < mRestoreSets.length; i++) {
5746 if (token == mRestoreSets[i].token) {
5747 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005748 mWakelock.acquire();
5749 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005750 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005751 mBackupHandler.sendMessage(msg);
5752 Binder.restoreCallingIdentity(oldId);
5753 return 0;
5754 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005755 }
5756 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005757
Joe Onorato8a9b2202010-02-26 18:56:32 -08005758 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005759 return -1;
5760 }
5761
Christopher Tate284f1bb2011-07-07 14:31:18 -07005762 public synchronized int restoreSome(long token, IRestoreObserver observer,
5763 String[] packages) {
5764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5765 "performRestore");
5766
5767 if (DEBUG) {
5768 StringBuilder b = new StringBuilder(128);
5769 b.append("restoreSome token=");
5770 b.append(Long.toHexString(token));
5771 b.append(" observer=");
5772 b.append(observer.toString());
5773 b.append(" packages=");
5774 if (packages == null) {
5775 b.append("null");
5776 } else {
5777 b.append('{');
5778 boolean first = true;
5779 for (String s : packages) {
5780 if (!first) {
5781 b.append(", ");
5782 } else first = false;
5783 b.append(s);
5784 }
5785 b.append('}');
5786 }
5787 Slog.d(TAG, b.toString());
5788 }
5789
5790 if (mEnded) {
5791 throw new IllegalStateException("Restore session already ended");
5792 }
5793
5794 if (mRestoreTransport == null || mRestoreSets == null) {
5795 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5796 return -1;
5797 }
5798
5799 if (mPackageName != null) {
5800 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5801 return -1;
5802 }
5803
5804 synchronized (mQueueLock) {
5805 for (int i = 0; i < mRestoreSets.length; i++) {
5806 if (token == mRestoreSets[i].token) {
5807 long oldId = Binder.clearCallingIdentity();
5808 mWakelock.acquire();
5809 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5810 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5811 packages, true);
5812 mBackupHandler.sendMessage(msg);
5813 Binder.restoreCallingIdentity(oldId);
5814 return 0;
5815 }
5816 }
5817 }
5818
5819 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5820 return -1;
5821 }
5822
Christopher Tate84725812010-02-04 15:52:40 -08005823 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005824 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005825
Christopher Tate73a3cb32010-12-13 18:27:26 -08005826 if (mEnded) {
5827 throw new IllegalStateException("Restore session already ended");
5828 }
5829
Chris Tate44ab8452010-11-16 15:10:49 -08005830 if (mPackageName != null) {
5831 if (! mPackageName.equals(packageName)) {
5832 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5833 + " on session for package " + mPackageName);
5834 return -1;
5835 }
5836 }
5837
Christopher Tate84725812010-02-04 15:52:40 -08005838 PackageInfo app = null;
5839 try {
5840 app = mPackageManager.getPackageInfo(packageName, 0);
5841 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005842 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005843 return -1;
5844 }
5845
5846 // If the caller is not privileged and is not coming from the target
5847 // app's uid, throw a permission exception back to the caller.
5848 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5849 Binder.getCallingPid(), Binder.getCallingUid());
5850 if ((perm == PackageManager.PERMISSION_DENIED) &&
5851 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005852 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005853 + " or calling uid=" + Binder.getCallingUid());
5854 throw new SecurityException("No permission to restore other packages");
5855 }
5856
Christopher Tate7d411a32010-02-26 11:27:08 -08005857 // If the package has no backup agent, we obviously cannot proceed
5858 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005859 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005860 return -1;
5861 }
5862
Christopher Tate84725812010-02-04 15:52:40 -08005863 // So far so good; we're allowed to try to restore this package. Now
5864 // check whether there is data for it in the current dataset, falling back
5865 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005866 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005867
5868 // If we didn't come up with a place to look -- no ancestral dataset and
5869 // the app has never been backed up from this device -- there's nothing
5870 // to do but return failure.
5871 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005872 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005873 return -1;
5874 }
5875
5876 // Ready to go: enqueue the restore request and claim success
5877 long oldId = Binder.clearCallingIdentity();
5878 mWakelock.acquire();
5879 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005880 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005881 mBackupHandler.sendMessage(msg);
5882 Binder.restoreCallingIdentity(oldId);
5883 return 0;
5884 }
5885
Christopher Tate73a3cb32010-12-13 18:27:26 -08005886 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5887 class EndRestoreRunnable implements Runnable {
5888 BackupManagerService mBackupManager;
5889 ActiveRestoreSession mSession;
5890
5891 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5892 mBackupManager = manager;
5893 mSession = session;
5894 }
5895
5896 public void run() {
5897 // clean up the session's bookkeeping
5898 synchronized (mSession) {
5899 try {
5900 if (mSession.mRestoreTransport != null) {
5901 mSession.mRestoreTransport.finishRestore();
5902 }
5903 } catch (Exception e) {
5904 Slog.e(TAG, "Error in finishRestore", e);
5905 } finally {
5906 mSession.mRestoreTransport = null;
5907 mSession.mEnded = true;
5908 }
5909 }
5910
5911 // clean up the BackupManagerService side of the bookkeeping
5912 // and cancel any pending timeout message
5913 mBackupManager.clearRestoreSession(mSession);
5914 }
5915 }
5916
Dan Egnor0084da52009-07-29 12:57:16 -07005917 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005918 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005919
Christopher Tate73a3cb32010-12-13 18:27:26 -08005920 if (mEnded) {
5921 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005922 }
5923
Christopher Tate73a3cb32010-12-13 18:27:26 -08005924 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005925 }
5926 }
5927
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005928 @Override
5929 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005930 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5931
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005932 long identityToken = Binder.clearCallingIdentity();
5933 try {
5934 dumpInternal(pw);
5935 } finally {
5936 Binder.restoreCallingIdentity(identityToken);
5937 }
5938 }
5939
5940 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005941 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005942 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005943 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005944 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005945 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005946 if (mBackupRunning) pw.println("Backup currently running");
5947 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005948 + " (now = " + System.currentTimeMillis() + ')');
5949 pw.println(" next scheduled: " + mNextBackupPass);
5950
Christopher Tate91717492009-06-26 21:07:13 -07005951 pw.println("Available transports:");
5952 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005953 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5954 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005955 IBackupTransport transport = getTransport(t);
5956 File dir = new File(mBaseStateDir, transport.transportDirName());
5957 pw.println(" destination: " + transport.currentDestinationString());
5958 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005959 for (File f : dir.listFiles()) {
5960 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5961 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005962 } catch (Exception e) {
5963 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005964 pw.println(" Error: " + e);
5965 }
Christopher Tate91717492009-06-26 21:07:13 -07005966 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005967
5968 pw.println("Pending init: " + mPendingInits.size());
5969 for (String s : mPendingInits) {
5970 pw.println(" " + s);
5971 }
5972
Christopher Tate6de74ff2012-01-17 15:20:32 -08005973 if (DEBUG_BACKUP_TRACE) {
5974 synchronized (mBackupTrace) {
5975 if (!mBackupTrace.isEmpty()) {
5976 pw.println("Most recent backup trace:");
5977 for (String s : mBackupTrace) {
5978 pw.println(" " + s);
5979 }
5980 }
5981 }
5982 }
5983
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005984 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005985 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005986 for (int i=0; i<N; i++) {
5987 int uid = mBackupParticipants.keyAt(i);
5988 pw.print(" uid: ");
5989 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005990 HashSet<String> participants = mBackupParticipants.valueAt(i);
5991 for (String app: participants) {
5992 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005993 }
5994 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005995
Christopher Tateb49ceb32010-02-08 16:22:24 -08005996 pw.println("Ancestral packages: "
5997 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005998 if (mAncestralPackages != null) {
5999 for (String pkg : mAncestralPackages) {
6000 pw.println(" " + pkg);
6001 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08006002 }
6003
Christopher Tate73e02522009-07-15 14:18:26 -07006004 pw.println("Ever backed up: " + mEverStoredApps.size());
6005 for (String pkg : mEverStoredApps) {
6006 pw.println(" " + pkg);
6007 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006008
6009 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07006010 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07006011 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07006012 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006013 }
6014 }
Christopher Tate487529a2009-04-29 14:03:25 -07006015}