blob: 2a3c87e4ff6f175eb33b9e3f615a2b66a8783baf [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;
rpcraigebab0ae2012-12-04 09:37:23 -050066import android.os.SELinux;
Christopher Tate32418be2011-10-10 13:51:12 -070067import android.os.ServiceManager;
Dan Egnorbb9001c2009-07-27 12:20:13 -070068import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070070import android.os.WorkSource;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070071import android.os.Environment.UserEnvironment;
Christopher Tate32418be2011-10-10 13:51:12 -070072import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080073import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070074import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070075import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080076import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070077import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070078import android.util.StringBuilderPrinter;
79
Jason parksa3cdaa52011-01-13 14:15:43 -060080import com.android.internal.backup.BackupConstants;
81import com.android.internal.backup.IBackupTransport;
Christopher Tate294b5122013-02-19 14:08:59 -080082import com.android.internal.backup.IObbBackupService;
Jason parksa3cdaa52011-01-13 14:15:43 -060083import com.android.internal.backup.LocalTransport;
84import com.android.server.PackageManagerBackupAgent.Metadata;
85
Christopher Tate2efd2db2011-07-19 16:32:49 -070086import java.io.BufferedInputStream;
87import java.io.BufferedOutputStream;
88import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070089import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070090import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070091import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070092import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070093import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070094import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080095import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070096import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070097import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070098import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070099import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700100import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -0700101import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700102import java.security.InvalidAlgorithmParameterException;
103import java.security.InvalidKeyException;
104import java.security.Key;
105import java.security.NoSuchAlgorithmException;
106import java.security.SecureRandom;
107import java.security.spec.InvalidKeySpecException;
108import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700109import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400110import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700111import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700112import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400113import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700114import java.util.HashSet;
115import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700116import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700117import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800118import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700119import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700120import java.util.zip.Deflater;
121import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700122import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700123
Christopher Tate2efd2db2011-07-19 16:32:49 -0700124import javax.crypto.BadPaddingException;
125import javax.crypto.Cipher;
126import javax.crypto.CipherInputStream;
127import javax.crypto.CipherOutputStream;
128import javax.crypto.IllegalBlockSizeException;
129import javax.crypto.NoSuchPaddingException;
130import javax.crypto.SecretKey;
131import javax.crypto.SecretKeyFactory;
132import javax.crypto.spec.IvParameterSpec;
133import javax.crypto.spec.PBEKeySpec;
134import javax.crypto.spec.SecretKeySpec;
135
Christopher Tate487529a2009-04-29 14:03:25 -0700136class BackupManagerService extends IBackupManager.Stub {
137 private static final String TAG = "BackupManagerService";
Christopher Tate559c6542013-02-12 14:57:04 -0800138 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700139 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700140
141 // Name and current contents version of the full-backup manifest file
142 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
143 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700144 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
145 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700146 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700147
Christopher Tate73d73692012-01-20 17:11:31 -0800148 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
149
Christopher Tate49401dd2009-07-01 12:34:29 -0700150 // How often we perform a backup pass. Privileged external callers can
151 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700152 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700153
Dan Egnorc1c49c02009-10-30 17:35:39 -0700154 // Random variation in backup scheduling time to avoid server load spikes
155 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
156
Christopher Tate8031a3d2009-07-06 16:36:05 -0700157 // The amount of time between the initial provisioning of the device and
158 // the first backup pass.
159 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
160
Christopher Tate45281862010-03-05 15:46:30 -0800161 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
162 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
163 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700164 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700165 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700166 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700167 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700168 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700169 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
170 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800171 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700172 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
173 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700174
Christopher Tate8e294d42011-08-31 20:37:12 -0700175 // backup task state machine tick
176 static final int MSG_BACKUP_RESTORE_STEP = 20;
177 static final int MSG_OP_COMPLETE = 21;
178
Christopher Tatec7b31e32009-06-10 15:49:30 -0700179 // Timeout interval for deciding that a bind or clear-data has taken too long
180 static final long TIMEOUT_INTERVAL = 10 * 1000;
181
Christopher Tate44a27902010-01-27 17:15:49 -0800182 // Timeout intervals for agent backup & restore operations
183 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700184 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700185 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800186 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
187
Christopher Tate2efd2db2011-07-19 16:32:49 -0700188 // User confirmation timeout for a full backup/restore operation. It's this long in
189 // order to give them time to enter the backup password.
190 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700191
Christopher Tate487529a2009-04-29 14:03:25 -0700192 private Context mContext;
193 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800194 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700195 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700196 private PowerManager mPowerManager;
197 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700198 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800199 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700200
Christopher Tate73e02522009-07-15 14:18:26 -0700201 boolean mEnabled; // access to this is synchronized on 'this'
202 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800203 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700204 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800205 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800206 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700207 PendingIntent mRunBackupIntent, mRunInitIntent;
208 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700209 // map UIDs to the set of participating packages under that UID
210 final SparseArray<HashSet<String>> mBackupParticipants
211 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700212 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700213 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700214 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700215
Christopher Tatecc55f812011-08-16 16:06:53 -0700216 BackupRequest(String pkgName) {
217 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700218 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700219
220 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700221 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700222 }
Christopher Tate46758122009-05-06 11:22:00 -0700223 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800224 // Backups that we haven't started yet. Keys are package names.
225 HashMap<String,BackupRequest> mPendingBackups
226 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700227
228 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700229 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700230
231 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700232 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700233
Christopher Tate043dadc2009-06-02 16:11:00 -0700234 // The thread performing the sequence of queued backups binds to each app's agent
235 // in succession. Bind notifications are asynchronously delivered through the
236 // Activity Manager; use this lock object to signal when a requested binding has
237 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700238 final Object mAgentConnectLock = new Object();
239 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700240 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700241 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700242 volatile long mLastBackupPass;
243 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700244
Christopher Tate6de74ff2012-01-17 15:20:32 -0800245 // For debugging, we maintain a progress trace of operations during backup
246 static final boolean DEBUG_BACKUP_TRACE = true;
247 final List<String> mBackupTrace = new ArrayList<String>();
248
Christopher Tate55f931a2009-09-29 17:17:34 -0700249 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700250 final Object mClearDataLock = new Object();
251 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700252
Christopher Tate91717492009-06-26 21:07:13 -0700253 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700254 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700255 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700256 String mCurrentTransport;
257 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800258 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700259
Christopher Tate97ea1222012-05-17 14:59:41 -0700260 // Watch the device provisioning operation during setup
261 ContentObserver mProvisionedObserver;
262
263 class ProvisionedObserver extends ContentObserver {
264 public ProvisionedObserver(Handler handler) {
265 super(handler);
266 }
267
268 public void onChange(boolean selfChange) {
269 final boolean wasProvisioned = mProvisioned;
270 final boolean isProvisioned = deviceIsProvisioned();
271 // latch: never unprovision
272 mProvisioned = wasProvisioned || isProvisioned;
273 if (MORE_DEBUG) {
274 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
275 + " is=" + isProvisioned + " now=" + mProvisioned);
276 }
277
278 synchronized (mQueueLock) {
279 if (mProvisioned && !wasProvisioned && mEnabled) {
280 // we're now good to go, so start the backup alarms
281 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
282 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
283 }
284 }
285 }
286 }
287
Christopher Tate2d449afe2010-03-29 19:14:24 -0700288 class RestoreGetSetsParams {
289 public IBackupTransport transport;
290 public ActiveRestoreSession session;
291 public IRestoreObserver observer;
292
293 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
294 IRestoreObserver _observer) {
295 transport = _transport;
296 session = _session;
297 observer = _observer;
298 }
299 }
300
Christopher Tate73e02522009-07-15 14:18:26 -0700301 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700302 public IBackupTransport transport;
303 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700304 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800305 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800306 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700307 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700308 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800309
310 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700311 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800312 transport = _transport;
313 observer = _obs;
314 token = _token;
315 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800316 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700317 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700318 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800319 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700320
Chris Tate249345b2010-10-29 12:57:04 -0700321 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
322 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700323 transport = _transport;
324 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700325 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800326 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800327 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700328 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700329 filterSet = null;
330 }
331
332 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
333 String[] _filterSet, boolean _needFullBackup) {
334 transport = _transport;
335 observer = _obs;
336 token = _token;
337 pkgInfo = null;
338 pmToken = 0;
339 needFullBackup = _needFullBackup;
340 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700341 }
342 }
343
Christopher Tate73e02522009-07-15 14:18:26 -0700344 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700345 public IBackupTransport transport;
346 public PackageInfo packageInfo;
347
348 ClearParams(IBackupTransport _transport, PackageInfo _info) {
349 transport = _transport;
350 packageInfo = _info;
351 }
352 }
353
Christopher Tate4a627c72011-04-01 14:43:32 -0700354 class FullParams {
355 public ParcelFileDescriptor fd;
356 public final AtomicBoolean latch;
357 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700358 public String curPassword; // filled in by the confirmation step
359 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700360
361 FullParams() {
362 latch = new AtomicBoolean(false);
363 }
364 }
365
366 class FullBackupParams extends FullParams {
367 public boolean includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -0800368 public boolean includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -0700369 public boolean includeShared;
370 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700371 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700372 public String[] packages;
373
Christopher Tate294b5122013-02-19 14:08:59 -0800374 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
375 boolean saveShared, boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700376 fd = output;
377 includeApks = saveApks;
Christopher Tate294b5122013-02-19 14:08:59 -0800378 includeObbs = saveObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -0700379 includeShared = saveShared;
380 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700381 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700382 packages = pkgList;
383 }
384 }
385
386 class FullRestoreParams extends FullParams {
387 FullRestoreParams(ParcelFileDescriptor input) {
388 fd = input;
389 }
390 }
391
Christopher Tate44a27902010-01-27 17:15:49 -0800392 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
393 // token is the index of the entry in the pending-operations list.
394 static final int OP_PENDING = 0;
395 static final int OP_ACKNOWLEDGED = 1;
396 static final int OP_TIMEOUT = -1;
397
Christopher Tate8e294d42011-08-31 20:37:12 -0700398 class Operation {
399 public int state;
400 public BackupRestoreTask callback;
401
402 Operation(int initialState, BackupRestoreTask callbackObj) {
403 state = initialState;
404 callback = callbackObj;
405 }
406 }
407 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800408 final Object mCurrentOpLock = new Object();
409 final Random mTokenGenerator = new Random();
410
Christopher Tate4a627c72011-04-01 14:43:32 -0700411 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
412
Christopher Tate5cb400b2009-06-25 16:03:14 -0700413 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700414 File mBaseStateDir;
415 File mDataDir;
416 File mJournalDir;
417 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700418
Christopher Tate2efd2db2011-07-19 16:32:49 -0700419 // Backup password, if any, and the file where it's saved. What is stored is not the
420 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
421 // persisted) salt. Validation is performed by running the challenge text through the
422 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
423 // the saved hash string, then the challenge text matches the originally supplied
424 // password text.
425 private final SecureRandom mRng = new SecureRandom();
426 private String mPasswordHash;
427 private File mPasswordHashFile;
428 private byte[] mPasswordSalt;
429
430 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
431 static final int PBKDF2_HASH_ROUNDS = 10000;
432 static final int PBKDF2_KEY_SIZE = 256; // bits
433 static final int PBKDF2_SALT_SIZE = 512; // bits
434 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
435
Christopher Tate84725812010-02-04 15:52:40 -0800436 // Keep a log of all the apps we've ever backed up, and what the
437 // dataset tokens are for both the current backup dataset and
438 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700439 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700440 HashSet<String> mEverStoredApps = new HashSet<String>();
441
Christopher Tateb49ceb32010-02-08 16:22:24 -0800442 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800443 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800444 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800445 long mAncestralToken = 0;
446 long mCurrentToken = 0;
447
Christopher Tate4cc86e12009-09-21 19:36:51 -0700448 // Persistently track the need to do a full init
449 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
450 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700451
Christopher Tate4a627c72011-04-01 14:43:32 -0700452 // Utility: build a new random integer token
453 int generateToken() {
454 int token;
455 do {
456 synchronized (mTokenGenerator) {
457 token = mTokenGenerator.nextInt();
458 }
459 } while (token < 0);
460 return token;
461 }
462
Christopher Tate44a27902010-01-27 17:15:49 -0800463 // ----- Asynchronous backup/restore handler thread -----
464
465 private class BackupHandler extends Handler {
466 public BackupHandler(Looper looper) {
467 super(looper);
468 }
469
470 public void handleMessage(Message msg) {
471
472 switch (msg.what) {
473 case MSG_RUN_BACKUP:
474 {
475 mLastBackupPass = System.currentTimeMillis();
476 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
477
478 IBackupTransport transport = getTransport(mCurrentTransport);
479 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800480 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700481 synchronized (mQueueLock) {
482 mBackupRunning = false;
483 }
Christopher Tate44a27902010-01-27 17:15:49 -0800484 mWakelock.release();
485 break;
486 }
487
488 // snapshot the pending-backup set and work on that
489 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800490 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800491 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800492 // Do we have any work to do? Construct the work queue
493 // then release the synchronization lock to actually run
494 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800495 if (mPendingBackups.size() > 0) {
496 for (BackupRequest b: mPendingBackups.values()) {
497 queue.add(b);
498 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800499 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800500 mPendingBackups.clear();
501
502 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800503 mJournal = null;
504
Christopher Tate44a27902010-01-27 17:15:49 -0800505 }
506 }
Christopher Tatec61da312010-02-05 10:41:27 -0800507
Christopher Tate8e294d42011-08-31 20:37:12 -0700508 // At this point, we have started a new journal file, and the old
509 // file identity is being passed to the backup processing task.
510 // When it completes successfully, that old journal file will be
511 // deleted. If we crash prior to that, the old journal is parsed
512 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800513 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700514 // Spin up a backup state sequence and set it running
515 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
516 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
517 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800518 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800519 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700520 synchronized (mQueueLock) {
521 mBackupRunning = false;
522 }
Christopher Tatec61da312010-02-05 10:41:27 -0800523 mWakelock.release();
524 }
Christopher Tate44a27902010-01-27 17:15:49 -0800525 break;
526 }
527
Christopher Tate8e294d42011-08-31 20:37:12 -0700528 case MSG_BACKUP_RESTORE_STEP:
529 {
530 try {
531 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
532 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
533 task.execute();
534 } catch (ClassCastException e) {
535 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
536 }
537 break;
538 }
539
540 case MSG_OP_COMPLETE:
541 {
542 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700543 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
544 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700545 } catch (ClassCastException e) {
546 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
547 }
548 break;
549 }
550
Christopher Tate44a27902010-01-27 17:15:49 -0800551 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700552 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700553 // TODO: refactor full backup to be a looper-based state machine
554 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700555 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700556 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
Christopher Tate294b5122013-02-19 14:08:59 -0800557 params.observer, params.includeApks, params.includeObbs,
Christopher Tate728a1c42011-07-28 18:03:03 -0700558 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700559 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700560 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800561 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700562 }
Christopher Tate44a27902010-01-27 17:15:49 -0800563
564 case MSG_RUN_RESTORE:
565 {
566 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700568 PerformRestoreTask task = new PerformRestoreTask(
569 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700570 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700571 params.needFullBackup, params.filterSet);
572 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
573 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800574 break;
575 }
576
Christopher Tate75a99702011-05-18 16:28:19 -0700577 case MSG_RUN_FULL_RESTORE:
578 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700579 // TODO: refactor full restore to be a looper-based state machine
580 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700581 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700582 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
583 params.curPassword, params.encryptPassword,
584 params.observer, params.latch);
585 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700586 break;
587 }
588
Christopher Tate44a27902010-01-27 17:15:49 -0800589 case MSG_RUN_CLEAR:
590 {
591 ClearParams params = (ClearParams)msg.obj;
592 (new PerformClearTask(params.transport, params.packageInfo)).run();
593 break;
594 }
595
596 case MSG_RUN_INITIALIZE:
597 {
598 HashSet<String> queue;
599
600 // Snapshot the pending-init queue and work on that
601 synchronized (mQueueLock) {
602 queue = new HashSet<String>(mPendingInits);
603 mPendingInits.clear();
604 }
605
606 (new PerformInitializeTask(queue)).run();
607 break;
608 }
609
Christopher Tate2d449afe2010-03-29 19:14:24 -0700610 case MSG_RUN_GET_RESTORE_SETS:
611 {
612 // Like other async operations, this is entered with the wakelock held
613 RestoreSet[] sets = null;
614 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
615 try {
616 sets = params.transport.getAvailableRestoreSets();
617 // cache the result in the active session
618 synchronized (params.session) {
619 params.session.mRestoreSets = sets;
620 }
621 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
622 } catch (Exception e) {
623 Slog.e(TAG, "Error from transport getting set list");
624 } finally {
625 if (params.observer != null) {
626 try {
627 params.observer.restoreSetsAvailable(sets);
628 } catch (RemoteException re) {
629 Slog.e(TAG, "Unable to report listing to observer");
630 } catch (Exception e) {
631 Slog.e(TAG, "Restore observer threw", e);
632 }
633 }
634
Christopher Tate2a935092011-03-03 17:30:32 -0800635 // Done: reset the session timeout clock
636 removeMessages(MSG_RESTORE_TIMEOUT);
637 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
638
Christopher Tate2d449afe2010-03-29 19:14:24 -0700639 mWakelock.release();
640 }
641 break;
642 }
643
Christopher Tate44a27902010-01-27 17:15:49 -0800644 case MSG_TIMEOUT:
645 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700646 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800647 break;
648 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800649
650 case MSG_RESTORE_TIMEOUT:
651 {
652 synchronized (BackupManagerService.this) {
653 if (mActiveRestoreSession != null) {
654 // Client app left the restore session dangling. We know that it
655 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700656 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800657 // up now.
658 Slog.w(TAG, "Restore session timed out; aborting");
659 post(mActiveRestoreSession.new EndRestoreRunnable(
660 BackupManagerService.this, mActiveRestoreSession));
661 }
662 }
663 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700664
665 case MSG_FULL_CONFIRMATION_TIMEOUT:
666 {
667 synchronized (mFullConfirmations) {
668 FullParams params = mFullConfirmations.get(msg.arg1);
669 if (params != null) {
670 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
671
672 // Release the waiter; timeout == completion
673 signalFullBackupRestoreCompletion(params);
674
675 // Remove the token from the set
676 mFullConfirmations.delete(msg.arg1);
677
678 // Report a timeout to the observer, if any
679 if (params.observer != null) {
680 try {
681 params.observer.onTimeout();
682 } catch (RemoteException e) {
683 /* don't care if the app has gone away */
684 }
685 }
686 } else {
687 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
688 }
689 }
690 break;
691 }
Christopher Tate44a27902010-01-27 17:15:49 -0800692 }
693 }
694 }
695
Christopher Tate6de74ff2012-01-17 15:20:32 -0800696 // ----- Debug-only backup operation trace -----
697 void addBackupTrace(String s) {
698 if (DEBUG_BACKUP_TRACE) {
699 synchronized (mBackupTrace) {
700 mBackupTrace.add(s);
701 }
702 }
703 }
704
705 void clearBackupTrace() {
706 if (DEBUG_BACKUP_TRACE) {
707 synchronized (mBackupTrace) {
708 mBackupTrace.clear();
709 }
710 }
711 }
712
Christopher Tate44a27902010-01-27 17:15:49 -0800713 // ----- Main service implementation -----
714
Christopher Tate487529a2009-04-29 14:03:25 -0700715 public BackupManagerService(Context context) {
716 mContext = context;
717 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700718 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700719 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700720
Christopher Tateb6787f22009-07-02 17:40:45 -0700721 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
722 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700723 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700724
Christopher Tate44a27902010-01-27 17:15:49 -0800725 mBackupManagerBinder = asInterface(asBinder());
726
727 // spin up the backup/restore handler thread
728 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
729 mHandlerThread.start();
730 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
731
Christopher Tate22b87872009-05-04 16:41:53 -0700732 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700733 final ContentResolver resolver = context.getContentResolver();
734 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700735 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700736 mProvisioned = Settings.Global.getInt(resolver,
737 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700738 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800739 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700740
741 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
742 resolver.registerContentObserver(
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700743 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
Christopher Tate97ea1222012-05-17 14:59:41 -0700744 false, mProvisionedObserver);
745
Oscar Montemayora8529f62009-11-18 10:14:20 -0800746 // If Encrypted file systems is enabled or disabled, this call will return the
747 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600748 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800749 mBaseStateDir.mkdirs();
rpcraigebab0ae2012-12-04 09:37:23 -0500750 if (!SELinux.restorecon(mBaseStateDir)) {
751 Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
752 }
Christopher Tatef4172472009-05-05 15:50:03 -0700753 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700754
Christopher Tate2efd2db2011-07-19 16:32:49 -0700755 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
756 if (mPasswordHashFile.exists()) {
757 FileInputStream fin = null;
758 DataInputStream in = null;
759 try {
760 fin = new FileInputStream(mPasswordHashFile);
761 in = new DataInputStream(new BufferedInputStream(fin));
762 // integer length of the salt array, followed by the salt,
763 // then the hex pw hash string
764 int saltLen = in.readInt();
765 byte[] salt = new byte[saltLen];
766 in.readFully(salt);
767 mPasswordHash = in.readUTF();
768 mPasswordSalt = salt;
769 } catch (IOException e) {
770 Slog.e(TAG, "Unable to read saved backup pw hash");
771 } finally {
772 try {
773 if (in != null) in.close();
774 if (fin != null) fin.close();
775 } catch (IOException e) {
776 Slog.w(TAG, "Unable to close streams");
777 }
778 }
779 }
780
Christopher Tate4cc86e12009-09-21 19:36:51 -0700781 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700782 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700783 IntentFilter filter = new IntentFilter();
784 filter.addAction(RUN_BACKUP_ACTION);
785 context.registerReceiver(mRunBackupReceiver, filter,
786 android.Manifest.permission.BACKUP, null);
787
788 mRunInitReceiver = new RunInitializeReceiver();
789 filter = new IntentFilter();
790 filter.addAction(RUN_INITIALIZE_ACTION);
791 context.registerReceiver(mRunInitReceiver, filter,
792 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700793
794 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700795 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
796 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
797
Christopher Tate4cc86e12009-09-21 19:36:51 -0700798 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
799 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
800 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
801
Christopher Tatecde87f42009-06-12 12:55:53 -0700802 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700803 mJournalDir = new File(mBaseStateDir, "pending");
804 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700805 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700806
Christopher Tate73e02522009-07-15 14:18:26 -0700807 // Set up the various sorts of package tracking we do
808 initPackageTracking();
809
Christopher Tateabce4e82009-06-18 18:35:32 -0700810 // Build our mapping of uid to backup client services. This implicitly
811 // schedules a backup pass on the Package Manager metadata the first
812 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700813 synchronized (mBackupParticipants) {
814 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700815 }
816
Dan Egnor87a02bc2009-06-17 02:30:10 -0700817 // Set up our transport options and initialize the default transport
818 // TODO: Have transports register themselves somehow?
819 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700820 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700821 ComponentName localName = new ComponentName(context, LocalTransport.class);
822 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700823
Christopher Tate91717492009-06-26 21:07:13 -0700824 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700825 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
826 Settings.Secure.BACKUP_TRANSPORT);
827 if ("".equals(mCurrentTransport)) {
828 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700829 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800830 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700831
832 // Attach to the Google backup transport. When this comes up, it will set
833 // itself as the current transport because we explicitly reset mCurrentTransport
834 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700835 ComponentName transportComponent = new ComponentName("com.google.android.backup",
836 "com.google.android.backup.BackupTransportService");
837 try {
838 // If there's something out there that is supposed to be the Google
839 // backup transport, make sure it's legitimately part of the OS build
840 // and not an app lying about its package name.
841 ApplicationInfo info = mPackageManager.getApplicationInfo(
842 transportComponent.getPackageName(), 0);
843 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
844 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
845 Intent intent = new Intent().setComponent(transportComponent);
Amith Yamasani27b89e62013-01-16 12:30:11 -0800846 context.bindServiceAsUser(intent, mGoogleConnection, Context.BIND_AUTO_CREATE,
847 UserHandle.OWNER);
Christopher Tatea32504f2010-04-21 17:58:07 -0700848 } else {
849 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
850 }
851 } catch (PackageManager.NameNotFoundException nnf) {
852 // No such package? No binding.
853 if (DEBUG) Slog.v(TAG, "Google transport not present");
854 }
Christopher Tateaa088442009-06-16 18:25:46 -0700855
Christopher Tatecde87f42009-06-12 12:55:53 -0700856 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700857 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700858 parseLeftoverJournals();
859
Christopher Tateb6787f22009-07-02 17:40:45 -0700860 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700861 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700862
863 // Start the backup passes going
864 setBackupEnabled(areEnabled);
865 }
866
867 private class RunBackupReceiver extends BroadcastReceiver {
868 public void onReceive(Context context, Intent intent) {
869 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700870 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700871 if (mPendingInits.size() > 0) {
872 // If there are pending init operations, we process those
873 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800874 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700875 try {
876 mAlarmManager.cancel(mRunInitIntent);
877 mRunInitIntent.send();
878 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800879 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700880 // can't really do more than bail here
881 }
882 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800883 // Don't run backups now if we're disabled or not yet
884 // fully set up.
885 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700886 if (!mBackupRunning) {
887 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700888
Christopher Tate336a6492011-10-05 16:05:43 -0700889 // Acquire the wakelock and pass it to the backup thread. it will
890 // be released once backup concludes.
891 mBackupRunning = true;
892 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700893
Christopher Tate336a6492011-10-05 16:05:43 -0700894 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
895 mBackupHandler.sendMessage(msg);
896 } else {
897 Slog.i(TAG, "Backup time but one already running");
898 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700899 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800900 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700901 }
902 }
903 }
904 }
905 }
906 }
907
908 private class RunInitializeReceiver extends BroadcastReceiver {
909 public void onReceive(Context context, Intent intent) {
910 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
911 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800912 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700913
914 // Acquire the wakelock and pass it to the init thread. it will
915 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700916 mWakelock.acquire();
917
Christopher Tate4cc86e12009-09-21 19:36:51 -0700918 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700919 mBackupHandler.sendMessage(msg);
920 }
921 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700922 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700923 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700924
Christopher Tate73e02522009-07-15 14:18:26 -0700925 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800926 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700927
Christopher Tate84725812010-02-04 15:52:40 -0800928 // Remember our ancestral dataset
929 mTokenFile = new File(mBaseStateDir, "ancestral");
930 try {
931 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800932 int version = tf.readInt();
933 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
934 mAncestralToken = tf.readLong();
935 mCurrentToken = tf.readLong();
936
937 int numPackages = tf.readInt();
938 if (numPackages >= 0) {
939 mAncestralPackages = new HashSet<String>();
940 for (int i = 0; i < numPackages; i++) {
941 String pkgName = tf.readUTF();
942 mAncestralPackages.add(pkgName);
943 }
944 }
945 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800946 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800947 } catch (FileNotFoundException fnf) {
948 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800949 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800950 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800951 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800952 }
953
Christopher Tatee97e8072009-07-15 16:45:50 -0700954 // Keep a log of what apps we've ever backed up. Because we might have
955 // rebooted in the middle of an operation that was removing something from
956 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700957 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700958 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700959
Christopher Tatee97e8072009-07-15 16:45:50 -0700960 // If we were in the middle of removing something from the ever-backed-up
961 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700962 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700963 if (tempProcessedFile.exists()) {
964 tempProcessedFile.delete();
965 }
966
Dan Egnor852f8e42009-09-30 11:20:45 -0700967 // If there are previous contents, parse them out then start a new
968 // file to continue the recordkeeping.
969 if (mEverStored.exists()) {
970 RandomAccessFile temp = null;
971 RandomAccessFile in = null;
972
973 try {
974 temp = new RandomAccessFile(tempProcessedFile, "rws");
975 in = new RandomAccessFile(mEverStored, "r");
976
977 while (true) {
978 PackageInfo info;
979 String pkg = in.readUTF();
980 try {
981 info = mPackageManager.getPackageInfo(pkg, 0);
982 mEverStoredApps.add(pkg);
983 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700984 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700985 } catch (NameNotFoundException e) {
986 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700987 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700988 }
989 }
990 } catch (EOFException e) {
991 // Once we've rewritten the backup history log, atomically replace the
992 // old one with the new one then reopen the file for continuing use.
993 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800994 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700995 }
996 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700998 } finally {
999 try { if (temp != null) temp.close(); } catch (IOException e) {}
1000 try { if (in != null) in.close(); } catch (IOException e) {}
1001 }
1002 }
1003
Christopher Tate73e02522009-07-15 14:18:26 -07001004 // Register for broadcasts about package install, etc., so we can
1005 // update the provider list.
1006 IntentFilter filter = new IntentFilter();
1007 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1008 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1009 filter.addDataScheme("package");
1010 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001011 // Register for events related to sdcard installation.
1012 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001013 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1014 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001015 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001016 }
1017
Christopher Tatecde87f42009-06-12 12:55:53 -07001018 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001019 for (File f : mJournalDir.listFiles()) {
1020 if (mJournal == null || f.compareTo(mJournal) != 0) {
1021 // This isn't the current journal, so it must be a leftover. Read
1022 // out the package names mentioned there and schedule them for
1023 // backup.
1024 RandomAccessFile in = null;
1025 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001026 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001027 in = new RandomAccessFile(f, "r");
1028 while (true) {
1029 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001030 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001031 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001032 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001033 } catch (EOFException e) {
1034 // no more data; we're done
1035 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001036 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001037 } finally {
1038 // close/delete the file
1039 try { if (in != null) in.close(); } catch (IOException e) {}
1040 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001041 }
1042 }
1043 }
1044 }
1045
Christopher Tate2efd2db2011-07-19 16:32:49 -07001046 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1047 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1048 }
1049
1050 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1051 try {
1052 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1053 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1054 return keyFactory.generateSecret(ks);
1055 } catch (InvalidKeySpecException e) {
1056 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1057 } catch (NoSuchAlgorithmException e) {
1058 Slog.e(TAG, "PBKDF2 unavailable!");
1059 }
1060 return null;
1061 }
1062
1063 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1064 SecretKey key = buildPasswordKey(pw, salt, rounds);
1065 if (key != null) {
1066 return byteArrayToHex(key.getEncoded());
1067 }
1068 return null;
1069 }
1070
1071 private String byteArrayToHex(byte[] data) {
1072 StringBuilder buf = new StringBuilder(data.length * 2);
1073 for (int i = 0; i < data.length; i++) {
1074 buf.append(Byte.toHexString(data[i], true));
1075 }
1076 return buf.toString();
1077 }
1078
1079 private byte[] hexToByteArray(String digits) {
1080 final int bytes = digits.length() / 2;
1081 if (2*bytes != digits.length()) {
1082 throw new IllegalArgumentException("Hex string must have an even number of digits");
1083 }
1084
1085 byte[] result = new byte[bytes];
1086 for (int i = 0; i < digits.length(); i += 2) {
1087 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1088 }
1089 return result;
1090 }
1091
1092 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1093 char[] mkAsChar = new char[pwBytes.length];
1094 for (int i = 0; i < pwBytes.length; i++) {
1095 mkAsChar[i] = (char) pwBytes[i];
1096 }
1097
1098 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1099 return checksum.getEncoded();
1100 }
1101
1102 // Used for generating random salts or passwords
1103 private byte[] randomBytes(int bits) {
1104 byte[] array = new byte[bits / 8];
1105 mRng.nextBytes(array);
1106 return array;
1107 }
1108
1109 // Backup password management
1110 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001111 // First, on an encrypted device we require matching the device pw
1112 final boolean isEncrypted;
1113 try {
1114 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1115 if (isEncrypted) {
1116 if (DEBUG) {
1117 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1118 }
1119 // 0 means the password validated
1120 // -2 means device not encrypted
1121 // Any other result is either password failure or an error condition,
1122 // so we refuse the match
1123 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1124 if (result == 0) {
1125 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1126 return true;
1127 } else if (result != -2) {
1128 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1129 return false;
1130 } else {
1131 // ...else the device is supposedly not encrypted. HOWEVER, the
1132 // query about the encryption state said that the device *is*
1133 // encrypted, so ... we may have a problem. Log it and refuse
1134 // the backup.
1135 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1136 return false;
1137 }
1138 }
1139 } catch (Exception e) {
1140 // Something went wrong talking to the mount service. This is very bad;
1141 // assume that we fail password validation.
1142 return false;
1143 }
1144
Christopher Tate2efd2db2011-07-19 16:32:49 -07001145 if (mPasswordHash == null) {
1146 // no current password case -- require that 'currentPw' be null or empty
1147 if (candidatePw == null || "".equals(candidatePw)) {
1148 return true;
1149 } // else the non-empty candidate does not match the empty stored pw
1150 } else {
1151 // hash the stated current pw and compare to the stored one
1152 if (candidatePw != null && candidatePw.length() > 0) {
1153 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1154 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1155 // candidate hash matches the stored hash -- the password matches
1156 return true;
1157 }
1158 } // else the stored pw is nonempty but the candidate is empty; no match
1159 }
1160 return false;
1161 }
1162
1163 @Override
1164 public boolean setBackupPassword(String currentPw, String newPw) {
1165 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1166 "setBackupPassword");
1167
1168 // If the supplied pw doesn't hash to the the saved one, fail
1169 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1170 return false;
1171 }
1172
1173 // Clearing the password is okay
1174 if (newPw == null || newPw.isEmpty()) {
1175 if (mPasswordHashFile.exists()) {
1176 if (!mPasswordHashFile.delete()) {
1177 // Unable to delete the old pw file, so fail
1178 Slog.e(TAG, "Unable to clear backup password");
1179 return false;
1180 }
1181 }
1182 mPasswordHash = null;
1183 mPasswordSalt = null;
1184 return true;
1185 }
1186
1187 try {
1188 // Okay, build the hash of the new backup password
1189 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1190 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1191
1192 OutputStream pwf = null, buffer = null;
1193 DataOutputStream out = null;
1194 try {
1195 pwf = new FileOutputStream(mPasswordHashFile);
1196 buffer = new BufferedOutputStream(pwf);
1197 out = new DataOutputStream(buffer);
1198 // integer length of the salt array, followed by the salt,
1199 // then the hex pw hash string
1200 out.writeInt(salt.length);
1201 out.write(salt);
1202 out.writeUTF(newPwHash);
1203 out.flush();
1204 mPasswordHash = newPwHash;
1205 mPasswordSalt = salt;
1206 return true;
1207 } finally {
1208 if (out != null) out.close();
1209 if (buffer != null) buffer.close();
1210 if (pwf != null) pwf.close();
1211 }
1212 } catch (IOException e) {
1213 Slog.e(TAG, "Unable to set backup password");
1214 }
1215 return false;
1216 }
1217
1218 @Override
1219 public boolean hasBackupPassword() {
1220 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1221 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001222
1223 try {
1224 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1225 || (mPasswordHash != null && mPasswordHash.length() > 0);
1226 } catch (Exception e) {
1227 // If we can't talk to the mount service we have a serious problem; fail
1228 // "secure" i.e. assuming that we require a password
1229 return true;
1230 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001231 }
1232
Christopher Tate4cc86e12009-09-21 19:36:51 -07001233 // Maintain persistent state around whether need to do an initialize operation.
1234 // Must be called with the queue lock held.
1235 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001237 + " on transport " + transportName);
1238 try {
1239 IBackupTransport transport = getTransport(transportName);
1240 String transportDirName = transport.transportDirName();
1241 File stateDir = new File(mBaseStateDir, transportDirName);
1242 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1243
1244 if (isPending) {
1245 // We need an init before we can proceed with sending backup data.
1246 // Record that with an entry in our set of pending inits, as well as
1247 // journaling it via creation of a sentinel file.
1248 mPendingInits.add(transportName);
1249 try {
1250 (new FileOutputStream(initPendingFile)).close();
1251 } catch (IOException ioe) {
1252 // Something is badly wrong with our permissions; just try to move on
1253 }
1254 } else {
1255 // No more initialization needed; wipe the journal and reset our state.
1256 initPendingFile.delete();
1257 mPendingInits.remove(transportName);
1258 }
1259 } catch (RemoteException e) {
1260 // can't happen; the transport is local
1261 }
1262 }
1263
Christopher Tated55e18a2009-09-21 10:12:59 -07001264 // Reset all of our bookkeeping, in response to having been told that
1265 // the backend data has been wiped [due to idle expiry, for example],
1266 // so we must re-upload all saved settings.
1267 void resetBackupState(File stateFileDir) {
1268 synchronized (mQueueLock) {
1269 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001270 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001271 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001272
Christopher Tate84725812010-02-04 15:52:40 -08001273 mCurrentToken = 0;
1274 writeRestoreTokens();
1275
Christopher Tated55e18a2009-09-21 10:12:59 -07001276 // Remove all the state files
1277 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001278 // ... but don't touch the needs-init sentinel
1279 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1280 sf.delete();
1281 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001282 }
Christopher Tate45597642011-04-04 16:59:21 -07001283 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001284
Christopher Tate45597642011-04-04 16:59:21 -07001285 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001286 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001287 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001288 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001289 HashSet<String> participants = mBackupParticipants.valueAt(i);
1290 if (participants != null) {
1291 for (String packageName : participants) {
1292 dataChangedImpl(packageName);
1293 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001294 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001295 }
1296 }
1297 }
1298
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001299 // Add a transport to our set of available backends. If 'transport' is null, this
1300 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001301 private void registerTransport(String name, IBackupTransport transport) {
1302 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001303 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001304 if (transport != null) {
1305 mTransports.put(name, transport);
1306 } else {
1307 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001308 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001309 mCurrentTransport = null;
1310 }
1311 // Nothing further to do in the unregistration case
1312 return;
1313 }
Christopher Tate91717492009-06-26 21:07:13 -07001314 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001315
1316 // If the init sentinel file exists, we need to be sure to perform the init
1317 // as soon as practical. We also create the state directory at registration
1318 // time to ensure it's present from the outset.
1319 try {
1320 String transportName = transport.transportDirName();
1321 File stateDir = new File(mBaseStateDir, transportName);
1322 stateDir.mkdirs();
1323
1324 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1325 if (initSentinel.exists()) {
1326 synchronized (mQueueLock) {
1327 mPendingInits.add(transportName);
1328
1329 // TODO: pick a better starting time than now + 1 minute
1330 long delay = 1000 * 60; // one minute, in milliseconds
1331 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1332 System.currentTimeMillis() + delay, mRunInitIntent);
1333 }
1334 }
1335 } catch (RemoteException e) {
1336 // can't happen, the transport is local
1337 }
Christopher Tate91717492009-06-26 21:07:13 -07001338 }
1339
Christopher Tate3799bc22009-05-06 16:13:56 -07001340 // ----- Track installation/removal of packages -----
1341 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1342 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001343 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001344
Christopher Tate3799bc22009-05-06 16:13:56 -07001345 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001346 boolean replacing = false;
1347 boolean added = false;
1348 Bundle extras = intent.getExtras();
1349 String pkgList[] = null;
1350 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001351 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001352 Uri uri = intent.getData();
1353 if (uri == null) {
1354 return;
1355 }
1356 String pkgName = uri.getSchemeSpecificPart();
1357 if (pkgName != null) {
1358 pkgList = new String[] { pkgName };
1359 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001360 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1361 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001362 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001363 added = true;
1364 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001365 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001366 added = false;
1367 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1368 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001369
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001370 if (pkgList == null || pkgList.length == 0) {
1371 return;
1372 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001373
1374 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001375 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001376 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001377 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001378 // This is the package-replaced case; we just remove the entry
1379 // under the old uid and fall through to re-add.
1380 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001381 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001382 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001384 } else {
1385 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001386 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1387 } else {
1388 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001389 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001390 }
1391 }
1392 }
1393 }
1394 };
1395
Dan Egnor87a02bc2009-06-17 02:30:10 -07001396 // ----- Track connection to GoogleBackupTransport service -----
1397 ServiceConnection mGoogleConnection = new ServiceConnection() {
1398 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001399 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001400 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001401 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001402 }
1403
1404 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001405 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001406 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001407 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001408 }
1409 };
1410
Christopher Tate0bacfd22012-01-11 14:41:19 -08001411 // Add the backup agents in the given packages to our set of known backup participants.
1412 // If 'packageNames' is null, adds all backup agents in the whole system.
1413 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001414 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001415 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001416 if (packageNames != null) {
1417 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1418 for (String packageName : packageNames) {
1419 addPackageParticipantsLockedInner(packageName, targetApps);
1420 }
1421 } else {
1422 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1423 addPackageParticipantsLockedInner(null, targetApps);
1424 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001425 }
1426
Christopher Tate181fafa2009-05-14 11:12:14 -07001427 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001428 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001429 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001430 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001431 }
1432
Dan Egnorefe52642009-06-24 00:16:33 -07001433 for (PackageInfo pkg : targetPkgs) {
1434 if (packageName == null || pkg.packageName.equals(packageName)) {
1435 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001436 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001437 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001438 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001439 mBackupParticipants.put(uid, set);
1440 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001441 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001442 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001443
Christopher Tatee82f68d2012-10-23 15:07:38 -07001444 // Schedule a backup for it on general principles
1445 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1446 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001447 }
Christopher Tate487529a2009-04-29 14:03:25 -07001448 }
1449 }
1450
Christopher Tate0bacfd22012-01-11 14:41:19 -08001451 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001452 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001453 if (packageNames == null) {
1454 Slog.w(TAG, "removePackageParticipants with null list");
1455 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001456 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001457
Christopher Tatea3d55342012-03-27 13:16:18 -07001458 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1459 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001460 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001461 // Known previous UID, so we know which package set to check
1462 HashSet<String> set = mBackupParticipants.get(oldUid);
1463 if (set != null && set.contains(pkg)) {
1464 removePackageFromSetLocked(set, pkg);
1465 if (set.isEmpty()) {
1466 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1467 mBackupParticipants.remove(oldUid);
1468 }
1469 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001470 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001471 }
1472
Christopher Tatea3d55342012-03-27 13:16:18 -07001473 private void removePackageFromSetLocked(final HashSet<String> set,
1474 final String packageName) {
1475 if (set.contains(packageName)) {
1476 // Found it. Remove this one package from the bookkeeping, and
1477 // if it's the last participating app under this uid we drop the
1478 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001479 // Note that we deliberately leave it 'known' in the "ever backed up"
1480 // bookkeeping so that its current-dataset data will be retrieved
1481 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001482 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001483 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001484 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001485 }
1486 }
1487
Christopher Tate181fafa2009-05-14 11:12:14 -07001488 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001489 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001490 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001491 int flags = PackageManager.GET_SIGNATURES;
1492 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1493 int N = packages.size();
1494 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001495 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001496 try {
1497 ApplicationInfo app = pkg.applicationInfo;
1498 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001499 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001500 packages.remove(a);
1501 }
1502 else {
1503 // we will need the shared library path, so look that up and store it here
1504 app = mPackageManager.getApplicationInfo(pkg.packageName,
1505 PackageManager.GET_SHARED_LIBRARY_FILES);
1506 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1507 }
1508 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001509 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001510 }
1511 }
Dan Egnorefe52642009-06-24 00:16:33 -07001512 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001513 }
Christopher Tateaa088442009-06-16 18:25:46 -07001514
Christopher Tate84725812010-02-04 15:52:40 -08001515 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001516 // backed up at least once
1517 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001518 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1519
1520 synchronized (mEverStoredApps) {
1521 if (!mEverStoredApps.add(packageName)) return;
1522
1523 RandomAccessFile out = null;
1524 try {
1525 out = new RandomAccessFile(mEverStored, "rws");
1526 out.seek(out.length());
1527 out.writeUTF(packageName);
1528 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001530 } finally {
1531 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001532 }
1533 }
1534 }
1535
Christopher Tatee97e8072009-07-15 16:45:50 -07001536 // Remove our awareness of having ever backed up the given package
1537 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001538 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1539 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001540
Dan Egnor852f8e42009-09-30 11:20:45 -07001541 synchronized (mEverStoredApps) {
1542 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1543 // we'll recognize on initialization time that the package no longer
1544 // exists and fix it up then.
1545 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1546 RandomAccessFile known = null;
1547 try {
1548 known = new RandomAccessFile(tempKnownFile, "rws");
1549 mEverStoredApps.remove(packageName);
1550 for (String s : mEverStoredApps) {
1551 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001552 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001553 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001554 known.close();
1555 known = null;
1556 if (!tempKnownFile.renameTo(mEverStored)) {
1557 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1558 }
1559 } catch (IOException e) {
1560 // Bad: we couldn't create the new copy. For safety's sake we
1561 // abandon the whole process and remove all what's-backed-up
1562 // state entirely, meaning we'll force a backup pass for every
1563 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001564 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001565 mEverStoredApps.clear();
1566 tempKnownFile.delete();
1567 mEverStored.delete();
1568 } finally {
1569 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001570 }
1571 }
1572 }
1573
Christopher Tateb49ceb32010-02-08 16:22:24 -08001574 // Persistently record the current and ancestral backup tokens as well
1575 // as the set of packages with data [supposedly] available in the
1576 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001577 void writeRestoreTokens() {
1578 try {
1579 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001580
1581 // First, the version number of this record, for futureproofing
1582 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1583
1584 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001585 af.writeLong(mAncestralToken);
1586 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001587
1588 // Now write the set of ancestral packages
1589 if (mAncestralPackages == null) {
1590 af.writeInt(-1);
1591 } else {
1592 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001593 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001594 for (String pkgName : mAncestralPackages) {
1595 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001596 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001597 }
1598 }
Christopher Tate84725812010-02-04 15:52:40 -08001599 af.close();
1600 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001602 }
1603 }
1604
Dan Egnor87a02bc2009-06-17 02:30:10 -07001605 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001606 private IBackupTransport getTransport(String transportName) {
1607 synchronized (mTransports) {
1608 IBackupTransport transport = mTransports.get(transportName);
1609 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001610 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001611 }
1612 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001613 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001614 }
1615
Christopher Tatedf01dea2009-06-09 20:45:02 -07001616 // fire off a backup agent, blocking until it attaches or times out
1617 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1618 IBackupAgent agent = null;
1619 synchronized(mAgentConnectLock) {
1620 mConnecting = true;
1621 mConnectedAgent = null;
1622 try {
1623 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001625
1626 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001627 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001628 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1629 while (mConnecting && mConnectedAgent == null
1630 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001631 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001632 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001633 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001634 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001635 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001636 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001637 return null;
1638 }
1639 }
1640
1641 // if we timed out with no connect, abort and move on
1642 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001644 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001645 return null;
1646 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001647 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001648 agent = mConnectedAgent;
1649 }
1650 } catch (RemoteException e) {
1651 // can't happen
1652 }
1653 }
1654 return agent;
1655 }
1656
Christopher Tatec7b31e32009-06-10 15:49:30 -07001657 // clear an application's data, blocking until the operation completes or times out
1658 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001659 // Don't wipe packages marked allowClearUserData=false
1660 try {
1661 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1662 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001663 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001664 + packageName);
1665 return;
1666 }
1667 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001668 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001669 return;
1670 }
1671
Christopher Tatec7b31e32009-06-10 15:49:30 -07001672 ClearDataObserver observer = new ClearDataObserver();
1673
1674 synchronized(mClearDataLock) {
1675 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001676 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001677 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001678 } catch (RemoteException e) {
1679 // can't happen because the activity manager is in this process
1680 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001681
1682 // only wait 10 seconds for the clear data to happen
1683 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1684 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1685 try {
1686 mClearDataLock.wait(5000);
1687 } catch (InterruptedException e) {
1688 // won't happen, but still.
1689 mClearingData = false;
1690 }
1691 }
1692 }
1693 }
1694
1695 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001696 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001697 synchronized(mClearDataLock) {
1698 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001699 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001700 }
1701 }
1702 }
1703
Christopher Tate1bb69062010-02-19 17:02:12 -08001704 // Get the restore-set token for the best-available restore set for this package:
1705 // the active set if possible, else the ancestral one. Returns zero if none available.
1706 long getAvailableRestoreToken(String packageName) {
1707 long token = mAncestralToken;
1708 synchronized (mQueueLock) {
1709 if (mEverStoredApps.contains(packageName)) {
1710 token = mCurrentToken;
1711 }
1712 }
1713 return token;
1714 }
1715
Christopher Tate44a27902010-01-27 17:15:49 -08001716 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001717 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1718
1719 interface BackupRestoreTask {
1720 // Execute one tick of whatever state machine the task implements
1721 void execute();
1722
1723 // An operation that wanted a callback has completed
1724 void operationComplete();
1725
1726 // An operation that wanted a callback has timed out
1727 void handleTimeout();
1728 }
1729
1730 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1731 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1732 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001733 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001734 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1735
1736 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1737 mBackupHandler.sendMessageDelayed(msg, interval);
1738 }
1739 }
1740
1741 // synchronous waiter case
1742 boolean waitUntilOperationComplete(int token) {
1743 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1744 + Integer.toHexString(token));
1745 int finalState = OP_PENDING;
1746 Operation op = null;
1747 synchronized (mCurrentOpLock) {
1748 while (true) {
1749 op = mCurrentOperations.get(token);
1750 if (op == null) {
1751 // mysterious disappearance: treat as success with no callback
1752 break;
1753 } else {
1754 if (op.state == OP_PENDING) {
1755 try {
1756 mCurrentOpLock.wait();
1757 } catch (InterruptedException e) {}
1758 // When the wait is notified we loop around and recheck the current state
1759 } else {
1760 // No longer pending; we're done
1761 finalState = op.state;
1762 break;
1763 }
Christopher Tate44a27902010-01-27 17:15:49 -08001764 }
Christopher Tate44a27902010-01-27 17:15:49 -08001765 }
1766 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001767
Christopher Tate44a27902010-01-27 17:15:49 -08001768 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001769 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001770 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001771 return finalState == OP_ACKNOWLEDGED;
1772 }
1773
Christopher Tate8e294d42011-08-31 20:37:12 -07001774 void handleTimeout(int token, Object obj) {
1775 // Notify any synchronous waiters
1776 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001777 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001778 op = mCurrentOperations.get(token);
1779 if (MORE_DEBUG) {
1780 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1781 + " but no op found");
1782 }
1783 int state = (op != null) ? op.state : OP_TIMEOUT;
1784 if (state == OP_PENDING) {
1785 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1786 op.state = OP_TIMEOUT;
1787 mCurrentOperations.put(token, op);
1788 }
1789 mCurrentOpLock.notifyAll();
1790 }
1791
1792 // If there's a TimeoutHandler for this event, call it
1793 if (op != null && op.callback != null) {
1794 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001795 }
Christopher Tate44a27902010-01-27 17:15:49 -08001796 }
1797
Christopher Tate043dadc2009-06-02 16:11:00 -07001798 // ----- Back up a set of applications via a worker thread -----
1799
Christopher Tate8e294d42011-08-31 20:37:12 -07001800 enum BackupState {
1801 INITIAL,
1802 RUNNING_QUEUE,
1803 FINAL
1804 }
1805
1806 class PerformBackupTask implements BackupRestoreTask {
1807 private static final String TAG = "PerformBackupTask";
1808
Christopher Tateaa088442009-06-16 18:25:46 -07001809 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001810 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001811 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001812 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001813 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001814 BackupState mCurrentState;
1815
1816 // carried information about the current in-flight operation
1817 PackageInfo mCurrentPackage;
1818 File mSavedStateName;
1819 File mBackupDataName;
1820 File mNewStateName;
1821 ParcelFileDescriptor mSavedState;
1822 ParcelFileDescriptor mBackupData;
1823 ParcelFileDescriptor mNewState;
1824 int mStatus;
1825 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001826
Christopher Tate44a27902010-01-27 17:15:49 -08001827 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001828 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001829 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001830 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001831 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001832
1833 try {
1834 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1835 } catch (RemoteException e) {
1836 // can't happen; the transport is local
1837 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001838
1839 mCurrentState = BackupState.INITIAL;
1840 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001841
1842 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001843 }
1844
Christopher Tate8e294d42011-08-31 20:37:12 -07001845 // Main entry point: perform one chunk of work, updating the state as appropriate
1846 // and reposting the next chunk to the primary backup handler thread.
1847 @Override
1848 public void execute() {
1849 switch (mCurrentState) {
1850 case INITIAL:
1851 beginBackup();
1852 break;
1853
1854 case RUNNING_QUEUE:
1855 invokeNextAgent();
1856 break;
1857
1858 case FINAL:
1859 if (!mFinished) finalizeBackup();
1860 else {
1861 Slog.e(TAG, "Duplicate finish");
1862 }
Christopher Tate2982d062011-09-06 20:35:24 -07001863 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001864 break;
1865 }
1866 }
1867
1868 // We're starting a backup pass. Initialize the transport and send
1869 // the PM metadata blob if we haven't already.
1870 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001871 if (DEBUG_BACKUP_TRACE) {
1872 clearBackupTrace();
1873 StringBuilder b = new StringBuilder(256);
1874 b.append("beginBackup: [");
1875 for (BackupRequest req : mOriginalQueue) {
1876 b.append(' ');
1877 b.append(req.packageName);
1878 }
1879 b.append(" ]");
1880 addBackupTrace(b.toString());
1881 }
1882
Christopher Tate8e294d42011-08-31 20:37:12 -07001883 mStatus = BackupConstants.TRANSPORT_OK;
1884
1885 // Sanity check: if the queue is empty we have no work to do.
1886 if (mOriginalQueue.isEmpty()) {
1887 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001888 addBackupTrace("queue empty at begin");
1889 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001890 return;
1891 }
1892
1893 // We need to retain the original queue contents in case of transport
1894 // failure, but we want a working copy that we can manipulate along
1895 // the way.
1896 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1897
Joe Onorato8a9b2202010-02-26 18:56:32 -08001898 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001899
Christopher Tate8e294d42011-08-31 20:37:12 -07001900 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001901 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001902 final String transportName = mTransport.transportDirName();
1903 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001904
Dan Egnor852f8e42009-09-30 11:20:45 -07001905 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001906 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001907 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001908 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001909 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001910 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001911
1912 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001913 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001914 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001915 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001916 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001917 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001918 }
Dan Egnor01445162009-09-21 17:04:05 -07001919 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001920
1921 // The package manager doesn't have a proper <application> etc, but since
1922 // it's running here in the system process we can just set up its agent
1923 // directly and use a synthetic BackupRequest. We always run this pass
1924 // because it's cheap and this way we guarantee that we don't get out of
1925 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001926 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001927 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1928 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001929 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001930 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001931 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001932 }
Christopher Tate90967f42009-09-20 15:28:33 -07001933
Christopher Tate8e294d42011-08-31 20:37:12 -07001934 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1935 // The backend reports that our dataset has been wiped. Note this in
1936 // the event log; the no-success code below will reset the backup
1937 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001938 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001939 }
1940 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001941 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001942 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001943 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001944 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001945 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1946 // metadata and its completion/timeout callback will continue the state
1947 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001948 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001949 if (mStatus != BackupConstants.TRANSPORT_OK) {
1950 // if things went wrong at this point, we need to
1951 // restage everything and try again later.
1952 resetBackupState(mStateDir); // Just to make sure.
1953 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001954 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001955 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001956 }
1957
Christopher Tate8e294d42011-08-31 20:37:12 -07001958 // Transport has been initialized and the PM metadata submitted successfully
1959 // if that was warranted. Now we process the single next thing in the queue.
1960 void invokeNextAgent() {
1961 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001962 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001963
Christopher Tate8e294d42011-08-31 20:37:12 -07001964 // Sanity check that we have work to do. If not, skip to the end where
1965 // we reestablish the wakelock invariants etc.
1966 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001967 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001968 executeNextState(BackupState.FINAL);
1969 return;
1970 }
1971
1972 // pop the entry we're going to process on this step
1973 BackupRequest request = mQueue.get(0);
1974 mQueue.remove(0);
1975
1976 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001977 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001978
1979 // Verify that the requested app exists; it might be something that
1980 // requested a backup but was then uninstalled. The request was
1981 // journalled and rather than tamper with the journal it's safer
1982 // to sanity-check here. This also gives us the classname of the
1983 // package's backup agent.
1984 try {
1985 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1986 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001987 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1988 // The manifest has changed but we had a stale backup request pending.
1989 // This won't happen again because the app won't be requesting further
1990 // backups.
1991 Slog.i(TAG, "Package " + request.packageName
1992 + " no longer supports backup; skipping");
1993 addBackupTrace("skipping - no agent, completion is noop");
1994 executeNextState(BackupState.RUNNING_QUEUE);
1995 return;
1996 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001997
Christopher Tate043dadc2009-06-02 16:11:00 -07001998 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001999 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002000 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2001 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07002002 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002003 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07002004 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002005 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2006 // at this point we'll either get a completion callback from the
2007 // agent, or a timeout message on the main handler. either way, we're
2008 // done here as long as we're successful so far.
2009 } else {
2010 // Timeout waiting for the agent
2011 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002012 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002013 } catch (SecurityException ex) {
2014 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002015 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002016 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002017 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002018 }
2019 } catch (NameNotFoundException e) {
2020 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002021 addBackupTrace("no such package");
2022 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002023 } finally {
2024 mWakelock.setWorkSource(null);
2025
2026 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002027 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002028 if (mStatus != BackupConstants.TRANSPORT_OK) {
2029 BackupState nextState = BackupState.RUNNING_QUEUE;
2030
2031 // An agent-level failure means we reenqueue this one agent for
2032 // a later retry, but otherwise proceed normally.
2033 if (mStatus == BackupConstants.AGENT_ERROR) {
2034 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2035 + " - restaging");
2036 dataChangedImpl(request.packageName);
2037 mStatus = BackupConstants.TRANSPORT_OK;
2038 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002039 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2040 // Failed lookup of the app, so we couldn't bring up an agent, but
2041 // we're otherwise fine. Just drop it and go on to the next as usual.
2042 mStatus = BackupConstants.TRANSPORT_OK;
2043 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002044 // Transport-level failure means we reenqueue everything
2045 revertAndEndBackup();
2046 nextState = BackupState.FINAL;
2047 }
2048
2049 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002050 } else {
2051 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002052 }
2053 }
2054 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002055
Christopher Tate8e294d42011-08-31 20:37:12 -07002056 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002057 addBackupTrace("finishing");
2058
Christopher Tate8e294d42011-08-31 20:37:12 -07002059 // Either backup was successful, in which case we of course do not need
2060 // this pass's journal any more; or it failed, in which case we just
2061 // re-enqueued all of these packages in the current active journal.
2062 // Either way, we no longer need this pass's journal.
2063 if (mJournal != null && !mJournal.delete()) {
2064 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2065 }
2066
2067 // If everything actually went through and this is the first time we've
2068 // done a backup, we can now record what the current backup dataset token
2069 // is.
2070 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002071 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002072 try {
2073 mCurrentToken = mTransport.getCurrentRestoreSet();
2074 } catch (RemoteException e) {} // can't happen
2075 writeRestoreTokens();
2076 }
2077
Christopher Tate336a6492011-10-05 16:05:43 -07002078 // Set up the next backup pass - at this point we can set mBackupRunning
2079 // to false to allow another pass to fire, because we're done with the
2080 // state machine sequence and the wakelock is refcounted.
2081 synchronized (mQueueLock) {
2082 mBackupRunning = false;
2083 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002084 // Make sure we back up everything and perform the one-time init
2085 clearMetadata();
2086 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002087 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002088 backupNow();
2089 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002090 }
2091
2092 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002093 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002094 Slog.i(TAG, "Backup pass finished.");
2095 mWakelock.release();
2096 }
2097
Christopher Tatee659fb92011-10-10 16:34:50 -07002098 // Remove the PM metadata state. This will generate an init on the next pass.
2099 void clearMetadata() {
2100 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2101 if (pmState.exists()) pmState.delete();
2102 }
2103
Christopher Tate8e294d42011-08-31 20:37:12 -07002104 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2105 // handler in case it doesn't get back to us.
2106 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002107 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002108 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2109 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002110
Christopher Tate8e294d42011-08-31 20:37:12 -07002111 mSavedStateName = new File(mStateDir, packageName);
2112 mBackupDataName = new File(mDataDir, packageName + ".data");
2113 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002114
Christopher Tate8e294d42011-08-31 20:37:12 -07002115 mSavedState = null;
2116 mBackupData = null;
2117 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002118
Christopher Tate4a627c72011-04-01 14:43:32 -07002119 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002120 try {
2121 // Look up the package info & signatures. This is first so that if it
2122 // throws an exception, there's no file setup yet that would need to
2123 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002124 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002125 // The metadata 'package' is synthetic; construct one and make
2126 // sure our global state is pointed at it
2127 mCurrentPackage = new PackageInfo();
2128 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002129 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002130
Christopher Tatec7b31e32009-06-10 15:49:30 -07002131 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002132 // the saved-state "file". This is by definition an incremental,
2133 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002134 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002135 ParcelFileDescriptor.MODE_READ_ONLY |
2136 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002137
Christopher Tate8e294d42011-08-31 20:37:12 -07002138 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002139 ParcelFileDescriptor.MODE_READ_WRITE |
2140 ParcelFileDescriptor.MODE_CREATE |
2141 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002142
rpcraigebab0ae2012-12-04 09:37:23 -05002143 if (!SELinux.restorecon(mBackupDataName)) {
2144 Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2145 }
2146
Christopher Tate8e294d42011-08-31 20:37:12 -07002147 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002148 ParcelFileDescriptor.MODE_READ_WRITE |
2149 ParcelFileDescriptor.MODE_CREATE |
2150 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002151
Christopher Tate44a27902010-01-27 17:15:49 -08002152 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002153 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002154 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002155 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002156 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002157 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002158 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002159 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002160 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2161 e.toString());
2162 agentErrorCleanup();
2163 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002164 }
2165
Christopher Tate8e294d42011-08-31 20:37:12 -07002166 // At this point the agent is off and running. The next thing to happen will
2167 // either be a callback from the agent, at which point we'll process its data
2168 // for transport, or a timeout. Either way the next phase will happen in
2169 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002170 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002171 return BackupConstants.TRANSPORT_OK;
2172 }
2173
2174 @Override
2175 public void operationComplete() {
2176 // Okay, the agent successfully reported back to us. Spin the data off to the
2177 // transport and proceed with the next stage.
2178 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2179 + mCurrentPackage.packageName);
2180 mBackupHandler.removeMessages(MSG_TIMEOUT);
2181 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002182 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002183
2184 ParcelFileDescriptor backupData = null;
2185 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002186 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002187 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002188 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002189 if (mStatus == BackupConstants.TRANSPORT_OK) {
2190 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002191 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002192 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002193 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002194 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002195
Dan Egnor83861e72009-09-17 16:17:55 -07002196 // TODO - We call finishBackup() for each application backed up, because
2197 // we need to know now whether it succeeded or failed. Instead, we should
2198 // hold off on finishBackup() until the end, which implies holding off on
2199 // renaming *all* the output state files (see below) until that happens.
2200
Christopher Tate6de74ff2012-01-17 15:20:32 -08002201 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002202 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002203 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002204 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002205 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002206 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002207 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002208 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002209 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002210 }
2211
2212 // After successful transport, delete the now-stale data
2213 // and juggle the files so that next time we supply the agent
2214 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002215 if (mStatus == BackupConstants.TRANSPORT_OK) {
2216 mBackupDataName.delete();
2217 mNewStateName.renameTo(mSavedStateName);
2218 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2219 mCurrentPackage.packageName, size);
2220 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002221 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002222 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2223 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002224 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002225 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002226 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2227 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2228 mCurrentPackage.packageName);
2229 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002230 } finally {
2231 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002232 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002233
Christopher Tate8e294d42011-08-31 20:37:12 -07002234 // If we encountered an error here it's a transport-level failure. That
2235 // means we need to halt everything and reschedule everything for next time.
2236 final BackupState nextState;
2237 if (mStatus != BackupConstants.TRANSPORT_OK) {
2238 revertAndEndBackup();
2239 nextState = BackupState.FINAL;
2240 } else {
2241 // Success! Proceed with the next app if any, otherwise we're done.
2242 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2243 }
2244
2245 executeNextState(nextState);
2246 }
2247
2248 @Override
2249 public void handleTimeout() {
2250 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2251 // it for the next time we run a backup pass.
2252 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2253 // fail repeatedly (i.e. have proved themselves to be buggy).
2254 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2255 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2256 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002257 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002258 agentErrorCleanup();
2259 dataChangedImpl(mCurrentPackage.packageName);
2260 }
2261
2262 void revertAndEndBackup() {
2263 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002264 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002265 for (BackupRequest request : mOriginalQueue) {
2266 dataChangedImpl(request.packageName);
2267 }
2268 // We also want to reset the backup schedule based on whatever
2269 // the transport suggests by way of retry/backoff time.
2270 restartBackupAlarm();
2271 }
2272
2273 void agentErrorCleanup() {
2274 mBackupDataName.delete();
2275 mNewStateName.delete();
2276 clearAgentState();
2277
2278 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2279 }
2280
2281 // Cleanup common to both success and failure cases
2282 void clearAgentState() {
2283 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2284 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2285 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2286 mSavedState = mBackupData = mNewState = null;
2287 synchronized (mCurrentOpLock) {
2288 mCurrentOperations.clear();
2289 }
2290
2291 // If this was a pseudopackage there's no associated Activity Manager state
2292 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002293 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002294 try { // unbind even on timeout, just in case
2295 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2296 } catch (RemoteException e) {}
2297 }
2298 }
2299
2300 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002301 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002302 synchronized (mQueueLock) {
2303 try {
2304 startBackupAlarmsLocked(mTransport.requestBackupTime());
2305 } catch (RemoteException e) { /* cannot happen */ }
2306 }
2307 }
2308
2309 void executeNextState(BackupState nextState) {
2310 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2311 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002312 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002313 mCurrentState = nextState;
2314 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2315 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002316 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002317 }
2318
Christopher Tatedf01dea2009-06-09 20:45:02 -07002319
Christopher Tate294b5122013-02-19 14:08:59 -08002320 // ----- Full backup/restore to a file/socket -----
Christopher Tate4a627c72011-04-01 14:43:32 -07002321
Christopher Tate294b5122013-02-19 14:08:59 -08002322 abstract class ObbServiceClient {
2323 public IObbBackupService mObbService;
2324 public void setObbBinder(IObbBackupService binder) {
2325 mObbService = binder;
2326 }
2327 }
2328
2329 class FullBackupObbConnection implements ServiceConnection {
2330 volatile IObbBackupService mService;
2331
2332 FullBackupObbConnection() {
2333 mService = null;
2334 }
2335
2336 public void establish() {
2337 if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2338 Intent obbIntent = new Intent().setComponent(new ComponentName(
2339 "com.android.sharedstoragebackup",
2340 "com.android.sharedstoragebackup.ObbBackupService"));
2341 BackupManagerService.this.mContext.bindService(
2342 obbIntent, this, Context.BIND_AUTO_CREATE);
2343 }
2344
2345 public void tearDown() {
2346 BackupManagerService.this.mContext.unbindService(this);
2347 }
2348
2349 public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2350 boolean success = false;
2351 waitForConnection();
2352
2353 ParcelFileDescriptor[] pipes = null;
2354 try {
2355 pipes = ParcelFileDescriptor.createPipe();
2356 int token = generateToken();
2357 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2358 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2359 routeSocketDataToOutput(pipes[0], out);
2360 success = waitUntilOperationComplete(token);
2361 } catch (Exception e) {
2362 Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2363 } finally {
2364 try {
2365 out.flush();
2366 if (pipes != null) {
2367 if (pipes[0] != null) pipes[0].close();
2368 if (pipes[1] != null) pipes[1].close();
2369 }
2370 } catch (IOException e) {
2371 Slog.w(TAG, "I/O error closing down OBB backup", e);
2372 }
2373 }
2374 return success;
2375 }
2376
2377 public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2378 long fileSize, int type, String path, long mode, long mtime,
2379 int token, IBackupManager callbackBinder) {
2380 waitForConnection();
2381
2382 try {
2383 mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2384 token, callbackBinder);
2385 } catch (Exception e) {
2386 Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2387 }
2388 }
2389
2390 private void waitForConnection() {
2391 synchronized (this) {
2392 while (mService == null) {
2393 if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2394 try {
2395 this.wait();
2396 } catch (InterruptedException e) { /* never interrupted */ }
2397 }
2398 if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2399 }
2400 }
2401
2402 @Override
2403 public void onServiceConnected(ComponentName name, IBinder service) {
2404 synchronized (this) {
2405 mService = IObbBackupService.Stub.asInterface(service);
2406 if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2407 + " connected on " + this);
2408 this.notifyAll();
2409 }
2410 }
2411
2412 @Override
2413 public void onServiceDisconnected(ComponentName name) {
2414 synchronized (this) {
2415 mService = null;
2416 if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2417 this.notifyAll();
2418 }
2419 }
2420
2421 }
2422
2423 private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2424 throws IOException {
2425 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2426 DataInputStream in = new DataInputStream(raw);
2427
2428 byte[] buffer = new byte[32 * 1024];
2429 int chunkTotal;
2430 while ((chunkTotal = in.readInt()) > 0) {
2431 while (chunkTotal > 0) {
2432 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2433 int nRead = in.read(buffer, 0, toRead);
2434 out.write(buffer, 0, nRead);
2435 chunkTotal -= nRead;
2436 }
2437 }
2438 }
2439
2440 class PerformFullBackupTask extends ObbServiceClient implements Runnable {
Christopher Tate4a627c72011-04-01 14:43:32 -07002441 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002442 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002443 IFullBackupRestoreObserver mObserver;
2444 boolean mIncludeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002445 boolean mIncludeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002446 boolean mIncludeShared;
2447 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002448 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002449 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002450 String mCurrentPassword;
2451 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002452 AtomicBoolean mLatchObject;
2453 File mFilesDir;
2454 File mManifestFile;
Christopher Tate294b5122013-02-19 14:08:59 -08002455
Christopher Tate4a627c72011-04-01 14:43:32 -07002456
Christopher Tate7926a692011-07-11 11:31:57 -07002457 class FullBackupRunner implements Runnable {
2458 PackageInfo mPackage;
2459 IBackupAgent mAgent;
2460 ParcelFileDescriptor mPipe;
2461 int mToken;
2462 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002463 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002464
2465 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002466 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002467 mPackage = pack;
2468 mAgent = agent;
2469 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2470 mToken = token;
2471 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002472 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002473 }
2474
2475 @Override
2476 public void run() {
2477 try {
2478 BackupDataOutput output = new BackupDataOutput(
2479 mPipe.getFileDescriptor());
2480
Christopher Tate73d73692012-01-20 17:11:31 -08002481 if (mWriteManifest) {
2482 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2483 writeAppManifest(mPackage, mManifestFile, mSendApk);
2484 FullBackup.backupToTar(mPackage.packageName, null, null,
2485 mFilesDir.getAbsolutePath(),
2486 mManifestFile.getAbsolutePath(),
2487 output);
2488 }
Christopher Tate7926a692011-07-11 11:31:57 -07002489
2490 if (mSendApk) {
2491 writeApkToBackup(mPackage, output);
2492 }
2493
Christopher Tatec58efa62011-08-01 19:20:14 -07002494 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002495 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002496 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2497 } catch (IOException e) {
2498 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2499 } catch (RemoteException e) {
2500 Slog.e(TAG, "Remote agent vanished during full backup of "
2501 + mPackage.packageName);
2502 } finally {
2503 try {
2504 mPipe.close();
2505 } catch (IOException e) {}
2506 }
2507 }
2508 }
2509
Christopher Tate4a627c72011-04-01 14:43:32 -07002510 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate294b5122013-02-19 14:08:59 -08002511 boolean includeApks, boolean includeObbs, boolean includeShared,
2512 String curPassword, String encryptPassword, boolean doAllApps,
2513 boolean doSystem, String[] packages, AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002514 mOutputFile = fd;
2515 mObserver = observer;
2516 mIncludeApks = includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002517 mIncludeObbs = includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002518 mIncludeShared = includeShared;
2519 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002520 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002521 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002522 mCurrentPassword = curPassword;
2523 // when backing up, if there is a current backup password, we require that
2524 // the user use a nonempty encryption password as well. if one is supplied
2525 // in the UI we use that, but if the UI was left empty we fall back to the
2526 // current backup password (which was supplied by the user as well).
2527 if (encryptPassword == null || "".equals(encryptPassword)) {
2528 mEncryptPassword = curPassword;
2529 } else {
2530 mEncryptPassword = encryptPassword;
2531 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002532 mLatchObject = latch;
2533
2534 mFilesDir = new File("/data/system");
2535 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2536 }
2537
2538 @Override
2539 public void run() {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002540 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate294b5122013-02-19 14:08:59 -08002541
2542 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
2543 FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2544 obbConnection.establish(); // we'll want this later
2545
Christopher Tate4a627c72011-04-01 14:43:32 -07002546 sendStartBackup();
2547
2548 // doAllApps supersedes the package set if any
2549 if (mAllApps) {
2550 packagesToBackup = mPackageManager.getInstalledPackages(
2551 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002552 // Exclude system apps if we've been asked to do so
2553 if (mIncludeSystem == false) {
2554 for (int i = 0; i < packagesToBackup.size(); ) {
2555 PackageInfo pkg = packagesToBackup.get(i);
2556 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2557 packagesToBackup.remove(i);
2558 } else {
2559 i++;
2560 }
2561 }
2562 }
2563 }
2564
2565 // Now process the command line argument packages, if any. Note that explicitly-
2566 // named system-partition packages will be included even if includeSystem was
2567 // set to false.
2568 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002569 for (String pkgName : mPackages) {
2570 try {
2571 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2572 PackageManager.GET_SIGNATURES));
2573 } catch (NameNotFoundException e) {
2574 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2575 }
2576 }
2577 }
2578
Christopher Tate73d73692012-01-20 17:11:31 -08002579 // Cull any packages that have indicated that backups are not permitted, as well
2580 // as any explicit mention of the 'special' shared-storage agent package (we
2581 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002582 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002583 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002584 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2585 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002586 packagesToBackup.remove(i);
2587 } else {
2588 i++;
2589 }
2590 }
2591
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002592 // Cull any packages that run as system-domain uids but do not define their
2593 // own backup agents
2594 for (int i = 0; i < packagesToBackup.size(); ) {
2595 PackageInfo pkg = packagesToBackup.get(i);
2596 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2597 && (pkg.applicationInfo.backupAgentName == null)) {
2598 if (MORE_DEBUG) {
2599 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2600 }
2601 packagesToBackup.remove(i);
2602 } else {
2603 i++;
2604 }
2605 }
2606
Christopher Tate7926a692011-07-11 11:31:57 -07002607 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002608 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002609
Christopher Tate4a627c72011-04-01 14:43:32 -07002610 PackageInfo pkg = null;
2611 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002612 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002613 boolean compressing = COMPRESS_FULL_BACKUPS;
2614 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002615
Christopher Tateeef4ae42011-08-05 13:15:53 -07002616 // Verify that the given password matches the currently-active
2617 // backup password, if any
2618 if (hasBackupPassword()) {
2619 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2620 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2621 return;
2622 }
2623 }
2624
Christopher Tate7bdb0962011-07-13 19:30:21 -07002625 // Write the global file header. All strings are UTF-8 encoded; lines end
2626 // with a '\n' byte. Actual backup data begins immediately following the
2627 // final '\n'.
2628 //
2629 // line 1: "ANDROID BACKUP"
2630 // line 2: backup file format version, currently "1"
2631 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002632 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2633 //
2634 // When line 4 is not "none", then additional header data follows:
2635 //
2636 // line 5: user password salt [hex]
2637 // line 6: master key checksum salt [hex]
2638 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2639 // line 8: IV of the user key [hex]
2640 // line 9: master key blob [hex]
2641 // IV of the master key, master key itself, master key checksum hash
2642 //
2643 // The master key checksum is the master key plus its checksum salt, run through
2644 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2645 // correct password for decrypting the archive: the master key decrypted from
2646 // the archive using the user-supplied password is also run through PBKDF2 in
2647 // this way, and if the result does not match the checksum as stored in the
2648 // archive, then we know that the user-supplied password does not match the
2649 // archive's.
2650 StringBuilder headerbuf = new StringBuilder(1024);
2651
Christopher Tate7bdb0962011-07-13 19:30:21 -07002652 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002653 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2654 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002655
2656 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002657 // Set up the encryption stage if appropriate, and emit the correct header
2658 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002659 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2660 } else {
2661 headerbuf.append("none\n");
2662 }
2663
Christopher Tate7bdb0962011-07-13 19:30:21 -07002664 byte[] header = headerbuf.toString().getBytes("UTF-8");
2665 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002666
2667 // Set up the compression stage feeding into the encryption stage (if any)
2668 if (compressing) {
2669 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2670 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2671 }
2672
2673 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002674 } catch (Exception e) {
2675 // Should never happen!
2676 Slog.e(TAG, "Unable to emit archive header", e);
2677 return;
2678 }
2679
Christopher Tate73d73692012-01-20 17:11:31 -08002680 // Shared storage if requested
2681 if (mIncludeShared) {
2682 try {
2683 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2684 packagesToBackup.add(pkg);
2685 } catch (NameNotFoundException e) {
2686 Slog.e(TAG, "Unable to find shared-storage backup handler");
2687 }
2688 }
2689
Christopher Tateb0628bf2011-06-02 15:08:13 -07002690 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002691 int N = packagesToBackup.size();
2692 for (int i = 0; i < N; i++) {
2693 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002694 backupOnePackage(pkg, out);
Christopher Tate294b5122013-02-19 14:08:59 -08002695
2696 // after the app's agent runs to handle its private filesystem
2697 // contents, back up any OBB content it has on its behalf.
2698 if (mIncludeObbs) {
2699 boolean obbOkay = obbConnection.backupObbs(pkg, out);
2700 if (!obbOkay) {
2701 throw new RuntimeException("Failure writing OBB stack for " + pkg);
2702 }
2703 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002704 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002705
Christopher Tate6853fcf2011-08-10 17:52:21 -07002706 // Done!
2707 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002708 } catch (RemoteException e) {
2709 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002710 } catch (Exception e) {
2711 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002712 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002713 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002714 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002715 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002716 mOutputFile.close();
2717 } catch (IOException e) {
2718 /* nothing we can do about this */
2719 }
2720 synchronized (mCurrentOpLock) {
2721 mCurrentOperations.clear();
2722 }
2723 synchronized (mLatchObject) {
2724 mLatchObject.set(true);
2725 mLatchObject.notifyAll();
2726 }
2727 sendEndBackup();
Christopher Tate294b5122013-02-19 14:08:59 -08002728 obbConnection.tearDown();
Christopher Tate4a627c72011-04-01 14:43:32 -07002729 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002730 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002731 }
2732 }
2733
Christopher Tate2efd2db2011-07-19 16:32:49 -07002734 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2735 OutputStream ofstream) throws Exception {
2736 // User key will be used to encrypt the master key.
2737 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002738 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002739 PBKDF2_HASH_ROUNDS);
2740
2741 // the master key is random for each backup
2742 byte[] masterPw = new byte[256 / 8];
2743 mRng.nextBytes(masterPw);
2744 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2745
2746 // primary encryption of the datastream with the random key
2747 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2748 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2749 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2750 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2751
2752 // line 4: name of encryption algorithm
2753 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2754 headerbuf.append('\n');
2755 // line 5: user password salt [hex]
2756 headerbuf.append(byteArrayToHex(newUserSalt));
2757 headerbuf.append('\n');
2758 // line 6: master key checksum salt [hex]
2759 headerbuf.append(byteArrayToHex(checksumSalt));
2760 headerbuf.append('\n');
2761 // line 7: number of PBKDF2 rounds used [decimal]
2762 headerbuf.append(PBKDF2_HASH_ROUNDS);
2763 headerbuf.append('\n');
2764
2765 // line 8: IV of the user key [hex]
2766 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2767 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2768
2769 byte[] IV = mkC.getIV();
2770 headerbuf.append(byteArrayToHex(IV));
2771 headerbuf.append('\n');
2772
2773 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2774 // [byte] IV length = Niv
2775 // [array of Niv bytes] IV itself
2776 // [byte] master key length = Nmk
2777 // [array of Nmk bytes] master key itself
2778 // [byte] MK checksum hash length = Nck
2779 // [array of Nck bytes] master key checksum hash
2780 //
2781 // The checksum is the (master key + checksum salt), run through the
2782 // stated number of PBKDF2 rounds
2783 IV = c.getIV();
2784 byte[] mk = masterKeySpec.getEncoded();
2785 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2786 checksumSalt, PBKDF2_HASH_ROUNDS);
2787
2788 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2789 + checksum.length + 3);
2790 DataOutputStream mkOut = new DataOutputStream(blob);
2791 mkOut.writeByte(IV.length);
2792 mkOut.write(IV);
2793 mkOut.writeByte(mk.length);
2794 mkOut.write(mk);
2795 mkOut.writeByte(checksum.length);
2796 mkOut.write(checksum);
2797 mkOut.flush();
2798 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2799 headerbuf.append(byteArrayToHex(encryptedMk));
2800 headerbuf.append('\n');
2801
2802 return finalOutput;
2803 }
2804
2805 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002806 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002807 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2808
2809 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2810 IApplicationThread.BACKUP_MODE_FULL);
2811 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002812 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002813 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002814 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002815
Christopher Tateb0628bf2011-06-02 15:08:13 -07002816 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002817 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002818 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002819 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002820 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2821 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2822 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2823
Christopher Tate73d73692012-01-20 17:11:31 -08002824 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002825
Christopher Tate7926a692011-07-11 11:31:57 -07002826 final int token = generateToken();
2827 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002828 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002829 pipes[1].close(); // the runner has dup'd it
2830 pipes[1] = null;
2831 Thread t = new Thread(runner);
2832 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002833
Christopher Tate7926a692011-07-11 11:31:57 -07002834 // Now pull data from the app and stuff it into the compressor
2835 try {
Christopher Tate294b5122013-02-19 14:08:59 -08002836 routeSocketDataToOutput(pipes[0], out);
Christopher Tate7926a692011-07-11 11:31:57 -07002837 } catch (IOException e) {
2838 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002839 }
2840
Christopher Tateb0628bf2011-06-02 15:08:13 -07002841 if (!waitUntilOperationComplete(token)) {
2842 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2843 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002844 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002845 }
Christopher Tate7926a692011-07-11 11:31:57 -07002846
Christopher Tateb0628bf2011-06-02 15:08:13 -07002847 } catch (IOException e) {
2848 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002849 } finally {
2850 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002851 // flush after every package
2852 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002853 if (pipes != null) {
2854 if (pipes[0] != null) pipes[0].close();
2855 if (pipes[1] != null) pipes[1].close();
2856 }
Christopher Tate7926a692011-07-11 11:31:57 -07002857 } catch (IOException e) {
2858 Slog.w(TAG, "Error bringing down backup stack");
2859 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002860 }
2861 } else {
2862 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2863 }
2864 tearDown(pkg);
2865 }
2866
Christopher Tate79ec80d2011-06-24 14:58:49 -07002867 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2868 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2869 final String appSourceDir = pkg.applicationInfo.sourceDir;
2870 final String apkDir = new File(appSourceDir).getParent();
2871 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2872 apkDir, appSourceDir, output);
2873
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002874 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2875 // doesn't have access to external storage.
2876
Christopher Tate79ec80d2011-06-24 14:58:49 -07002877 // Save associated .obb content if it exists and we did save the apk
2878 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002879 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2880 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002881 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002882 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002883 File[] obbFiles = obbDir.listFiles();
2884 if (obbFiles != null) {
2885 final String obbDirName = obbDir.getAbsolutePath();
2886 for (File obb : obbFiles) {
2887 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2888 obbDirName, obb.getAbsolutePath(), output);
2889 }
2890 }
2891 }
2892 }
2893
Christopher Tate6853fcf2011-08-10 17:52:21 -07002894 private void finalizeBackup(OutputStream out) {
2895 try {
2896 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2897 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2898 out.write(eof);
2899 } catch (IOException e) {
2900 Slog.w(TAG, "Error attempting to finalize backup stream");
2901 }
2902 }
2903
Christopher Tate4a627c72011-04-01 14:43:32 -07002904 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2905 throws IOException {
2906 // Manifest format. All data are strings ending in LF:
2907 // BACKUP_MANIFEST_VERSION, currently 1
2908 //
2909 // Version 1:
2910 // package name
2911 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002912 // platform versionCode
2913 // getInstallerPackageName() for this package (maybe empty)
2914 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002915 // number of signatures == N
2916 // N*: signature byte array in ascii format per Signature.toCharsString()
2917 StringBuilder builder = new StringBuilder(4096);
2918 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2919
2920 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2921 printer.println(pkg.packageName);
2922 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002923 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2924
2925 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2926 printer.println((installerName != null) ? installerName : "");
2927
Christopher Tate4a627c72011-04-01 14:43:32 -07002928 printer.println(withApk ? "1" : "0");
2929 if (pkg.signatures == null) {
2930 printer.println("0");
2931 } else {
2932 printer.println(Integer.toString(pkg.signatures.length));
2933 for (Signature sig : pkg.signatures) {
2934 printer.println(sig.toCharsString());
2935 }
2936 }
2937
2938 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002939 outstream.write(builder.toString().getBytes());
2940 outstream.close();
2941 }
2942
2943 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002944 if (pkg != null) {
2945 final ApplicationInfo app = pkg.applicationInfo;
2946 if (app != null) {
2947 try {
2948 // unbind and tidy up even on timeout or failure, just in case
2949 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002950
Christopher Tateb0628bf2011-06-02 15:08:13 -07002951 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002952 if (app.uid != Process.SYSTEM_UID
2953 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002954 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002955 mActivityManager.killApplicationProcess(app.processName, app.uid);
2956 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002957 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002958 }
2959 } catch (RemoteException e) {
2960 Slog.d(TAG, "Lost app trying to shut down");
2961 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002962 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002963 }
2964 }
2965
2966 // wrappers for observer use
2967 void sendStartBackup() {
2968 if (mObserver != null) {
2969 try {
2970 mObserver.onStartBackup();
2971 } catch (RemoteException e) {
2972 Slog.w(TAG, "full backup observer went away: startBackup");
2973 mObserver = null;
2974 }
2975 }
2976 }
2977
2978 void sendOnBackupPackage(String name) {
2979 if (mObserver != null) {
2980 try {
2981 // TODO: use a more user-friendly name string
2982 mObserver.onBackupPackage(name);
2983 } catch (RemoteException e) {
2984 Slog.w(TAG, "full backup observer went away: backupPackage");
2985 mObserver = null;
2986 }
2987 }
2988 }
2989
2990 void sendEndBackup() {
2991 if (mObserver != null) {
2992 try {
2993 mObserver.onEndBackup();
2994 } catch (RemoteException e) {
2995 Slog.w(TAG, "full backup observer went away: endBackup");
2996 mObserver = null;
2997 }
2998 }
2999 }
3000 }
3001
3002
Christopher Tate75a99702011-05-18 16:28:19 -07003003 // ----- Full restore from a file/socket -----
3004
3005 // Description of a file in the restore datastream
3006 static class FileMetadata {
3007 String packageName; // name of the owning app
3008 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07003009 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07003010 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
3011 String path; // subpath within the semantic domain
3012 long mode; // e.g. 0666 (actually int)
3013 long mtime; // last mod time, UTC time_t (actually int)
3014 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003015
3016 @Override
3017 public String toString() {
3018 StringBuilder sb = new StringBuilder(128);
3019 sb.append("FileMetadata{");
3020 sb.append(packageName); sb.append(',');
3021 sb.append(type); sb.append(',');
3022 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3023 sb.append(size);
3024 sb.append('}');
3025 return sb.toString();
3026 }
Christopher Tate75a99702011-05-18 16:28:19 -07003027 }
3028
3029 enum RestorePolicy {
3030 IGNORE,
3031 ACCEPT,
3032 ACCEPT_IF_APK
3033 }
3034
Christopher Tate294b5122013-02-19 14:08:59 -08003035 class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
Christopher Tate75a99702011-05-18 16:28:19 -07003036 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07003037 String mCurrentPassword;
3038 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003039 IFullBackupRestoreObserver mObserver;
3040 AtomicBoolean mLatchObject;
3041 IBackupAgent mAgent;
3042 String mAgentPackage;
3043 ApplicationInfo mTargetApp;
Christopher Tate294b5122013-02-19 14:08:59 -08003044 FullBackupObbConnection mObbConnection = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003045 ParcelFileDescriptor[] mPipes = null;
3046
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003047 long mBytes;
3048
Christopher Tate75a99702011-05-18 16:28:19 -07003049 // possible handling states for a given package in the restore dataset
3050 final HashMap<String, RestorePolicy> mPackagePolicies
3051 = new HashMap<String, RestorePolicy>();
3052
3053 // installer package names for each encountered app, derived from the manifests
3054 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3055
3056 // Signatures for a given package found in its manifest file
3057 final HashMap<String, Signature[]> mManifestSignatures
3058 = new HashMap<String, Signature[]>();
3059
3060 // Packages we've already wiped data on when restoring their first file
3061 final HashSet<String> mClearedPackages = new HashSet<String>();
3062
Christopher Tate728a1c42011-07-28 18:03:03 -07003063 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003064 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07003065 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07003066 mCurrentPassword = curPassword;
3067 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003068 mObserver = observer;
3069 mLatchObject = latch;
3070 mAgent = null;
3071 mAgentPackage = null;
3072 mTargetApp = null;
Christopher Tate294b5122013-02-19 14:08:59 -08003073 mObbConnection = new FullBackupObbConnection();
Christopher Tate75a99702011-05-18 16:28:19 -07003074
3075 // Which packages we've already wiped data on. We prepopulate this
3076 // with a whitelist of packages known to be unclearable.
3077 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07003078 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07003079
Christopher Tate75a99702011-05-18 16:28:19 -07003080 }
3081
3082 class RestoreFileRunnable implements Runnable {
3083 IBackupAgent mAgent;
3084 FileMetadata mInfo;
3085 ParcelFileDescriptor mSocket;
3086 int mToken;
3087
3088 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3089 ParcelFileDescriptor socket, int token) throws IOException {
3090 mAgent = agent;
3091 mInfo = info;
3092 mToken = token;
3093
3094 // This class is used strictly for process-local binder invocations. The
3095 // semantics of ParcelFileDescriptor differ in this case; in particular, we
3096 // do not automatically get a 'dup'ed descriptor that we can can continue
3097 // to use asynchronously from the caller. So, we make sure to dup it ourselves
3098 // before proceeding to do the restore.
3099 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3100 }
3101
3102 @Override
3103 public void run() {
3104 try {
3105 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3106 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3107 mToken, mBackupManagerBinder);
3108 } catch (RemoteException e) {
3109 // never happens; this is used strictly for local binder calls
3110 }
3111 }
3112 }
3113
3114 @Override
3115 public void run() {
3116 Slog.i(TAG, "--- Performing full-dataset restore ---");
Christopher Tate294b5122013-02-19 14:08:59 -08003117 mObbConnection.establish();
Christopher Tate75a99702011-05-18 16:28:19 -07003118 sendStartRestore();
3119
Christopher Tateb0628bf2011-06-02 15:08:13 -07003120 // Are we able to restore shared-storage data?
3121 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08003122 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07003123 }
3124
Christopher Tate2efd2db2011-07-19 16:32:49 -07003125 FileInputStream rawInStream = null;
3126 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003127 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07003128 if (hasBackupPassword()) {
3129 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
3130 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3131 return;
3132 }
3133 }
3134
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003135 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003136 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003137 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3138 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003139
3140 // First, parse out the unencrypted/uncompressed header
3141 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003142 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003143 final InputStream in;
3144
3145 boolean okay = false;
3146 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3147 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003148 rawDataIn.readFully(streamHeader);
3149 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3150 if (Arrays.equals(magicBytes, streamHeader)) {
3151 // okay, header looks good. now parse out the rest of the fields.
3152 String s = readHeaderLine(rawInStream);
3153 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3154 // okay, it's a version we recognize
3155 s = readHeaderLine(rawInStream);
3156 compressed = (Integer.parseInt(s) != 0);
3157 s = readHeaderLine(rawInStream);
3158 if (s.equals("none")) {
3159 // no more header to parse; we're good to go
3160 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003161 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003162 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3163 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003164 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003165 }
3166 } else Slog.w(TAG, "Archive is encrypted but no password given");
3167 } else Slog.w(TAG, "Wrong header version: " + s);
3168 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003169
3170 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003171 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003172 return;
3173 }
3174
3175 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003176 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003177
3178 boolean didRestore;
3179 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003180 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003181 } while (didRestore);
3182
Christopher Tatec58efa62011-08-01 19:20:14 -07003183 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003184 } catch (IOException e) {
3185 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003186 } finally {
3187 tearDownPipes();
3188 tearDownAgent(mTargetApp);
3189
3190 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003191 if (rawDataIn != null) rawDataIn.close();
3192 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003193 mInputFile.close();
3194 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003195 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003196 /* nothing we can do about this */
3197 }
3198 synchronized (mCurrentOpLock) {
3199 mCurrentOperations.clear();
3200 }
3201 synchronized (mLatchObject) {
3202 mLatchObject.set(true);
3203 mLatchObject.notifyAll();
3204 }
Christopher Tate294b5122013-02-19 14:08:59 -08003205 mObbConnection.tearDown();
Christopher Tate75a99702011-05-18 16:28:19 -07003206 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003207 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003208 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003209 }
3210 }
3211
Christopher Tate7bdb0962011-07-13 19:30:21 -07003212 String readHeaderLine(InputStream in) throws IOException {
3213 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003214 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003215 while ((c = in.read()) >= 0) {
3216 if (c == '\n') break; // consume and discard the newlines
3217 buffer.append((char)c);
3218 }
3219 return buffer.toString();
3220 }
3221
Christopher Tate2efd2db2011-07-19 16:32:49 -07003222 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3223 InputStream result = null;
3224 try {
3225 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3226
3227 String userSaltHex = readHeaderLine(rawInStream); // 5
3228 byte[] userSalt = hexToByteArray(userSaltHex);
3229
3230 String ckSaltHex = readHeaderLine(rawInStream); // 6
3231 byte[] ckSalt = hexToByteArray(ckSaltHex);
3232
3233 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3234 String userIvHex = readHeaderLine(rawInStream); // 8
3235
3236 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3237
3238 // decrypt the master key blob
3239 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003240 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003241 rounds);
3242 byte[] IV = hexToByteArray(userIvHex);
3243 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3244 c.init(Cipher.DECRYPT_MODE,
3245 new SecretKeySpec(userKey.getEncoded(), "AES"),
3246 ivSpec);
3247 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3248 byte[] mkBlob = c.doFinal(mkCipher);
3249
3250 // first, the master key IV
3251 int offset = 0;
3252 int len = mkBlob[offset++];
3253 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3254 offset += len;
3255 // then the master key itself
3256 len = mkBlob[offset++];
3257 byte[] mk = Arrays.copyOfRange(mkBlob,
3258 offset, offset + len);
3259 offset += len;
3260 // and finally the master key checksum hash
3261 len = mkBlob[offset++];
3262 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3263 offset, offset + len);
3264
3265 // now validate the decrypted master key against the checksum
3266 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3267 if (Arrays.equals(calculatedCk, mkChecksum)) {
3268 ivSpec = new IvParameterSpec(IV);
3269 c.init(Cipher.DECRYPT_MODE,
3270 new SecretKeySpec(mk, "AES"),
3271 ivSpec);
3272 // Only if all of the above worked properly will 'result' be assigned
3273 result = new CipherInputStream(rawInStream, c);
3274 } else Slog.w(TAG, "Incorrect password");
3275 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3276 } catch (InvalidAlgorithmParameterException e) {
3277 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3278 } catch (BadPaddingException e) {
3279 // This case frequently occurs when the wrong password is used to decrypt
3280 // the master key. Use the identical "incorrect password" log text as is
3281 // used in the checksum failure log in order to avoid providing additional
3282 // information to an attacker.
3283 Slog.w(TAG, "Incorrect password");
3284 } catch (IllegalBlockSizeException e) {
3285 Slog.w(TAG, "Invalid block size in master key");
3286 } catch (NoSuchAlgorithmException e) {
3287 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3288 } catch (NoSuchPaddingException e) {
3289 Slog.e(TAG, "Needed padding mechanism unavailable!");
3290 } catch (InvalidKeyException e) {
3291 Slog.w(TAG, "Illegal password; aborting");
3292 } catch (NumberFormatException e) {
3293 Slog.w(TAG, "Can't parse restore data header");
3294 } catch (IOException e) {
3295 Slog.w(TAG, "Can't read input header");
3296 }
3297
3298 return result;
3299 }
3300
Christopher Tate75a99702011-05-18 16:28:19 -07003301 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3302 FileMetadata info;
3303 try {
3304 info = readTarHeaders(instream);
3305 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003306 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003307 dumpFileMetadata(info);
3308 }
3309
3310 final String pkg = info.packageName;
3311 if (!pkg.equals(mAgentPackage)) {
3312 // okay, change in package; set up our various
3313 // bookkeeping if we haven't seen it yet
3314 if (!mPackagePolicies.containsKey(pkg)) {
3315 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3316 }
3317
3318 // Clean up the previous agent relationship if necessary,
3319 // and let the observer know we're considering a new app.
3320 if (mAgent != null) {
3321 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3322 tearDownPipes();
3323 tearDownAgent(mTargetApp);
3324 mTargetApp = null;
3325 mAgentPackage = null;
3326 }
3327 }
3328
3329 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3330 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3331 mPackageInstallers.put(pkg, info.installerPackageName);
3332 // We've read only the manifest content itself at this point,
3333 // so consume the footer before looping around to the next
3334 // input file
3335 skipTarPadding(info.size, instream);
3336 sendOnRestorePackage(pkg);
3337 } else {
3338 // Non-manifest, so it's actual file data. Is this a package
3339 // we're ignoring?
3340 boolean okay = true;
3341 RestorePolicy policy = mPackagePolicies.get(pkg);
3342 switch (policy) {
3343 case IGNORE:
3344 okay = false;
3345 break;
3346
3347 case ACCEPT_IF_APK:
3348 // If we're in accept-if-apk state, then the first file we
3349 // see MUST be the apk.
3350 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3351 if (DEBUG) Slog.d(TAG, "APK file; installing");
3352 // Try to install the app.
3353 String installerName = mPackageInstallers.get(pkg);
3354 okay = installApk(info, installerName, instream);
3355 // good to go; promote to ACCEPT
3356 mPackagePolicies.put(pkg, (okay)
3357 ? RestorePolicy.ACCEPT
3358 : RestorePolicy.IGNORE);
3359 // At this point we've consumed this file entry
3360 // ourselves, so just strip the tar footer and
3361 // go on to the next file in the input stream
3362 skipTarPadding(info.size, instream);
3363 return true;
3364 } else {
3365 // File data before (or without) the apk. We can't
3366 // handle it coherently in this case so ignore it.
3367 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3368 okay = false;
3369 }
3370 break;
3371
3372 case ACCEPT:
3373 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3374 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3375 // we can take the data without the apk, so we
3376 // *want* to do so. skip the apk by declaring this
3377 // one file not-okay without changing the restore
3378 // policy for the package.
3379 okay = false;
3380 }
3381 break;
3382
3383 default:
3384 // Something has gone dreadfully wrong when determining
3385 // the restore policy from the manifest. Ignore the
3386 // rest of this package's data.
3387 Slog.e(TAG, "Invalid policy from manifest");
3388 okay = false;
3389 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3390 break;
3391 }
3392
3393 // If the policy is satisfied, go ahead and set up to pipe the
3394 // data to the agent.
3395 if (DEBUG && okay && mAgent != null) {
3396 Slog.i(TAG, "Reusing existing agent instance");
3397 }
3398 if (okay && mAgent == null) {
3399 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3400
3401 try {
3402 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3403
3404 // If we haven't sent any data to this app yet, we probably
3405 // need to clear it first. Check that.
3406 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003407 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003408 // responsible for coherently managing a full
3409 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003410 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003411 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3412 clearApplicationDataSynchronous(pkg);
3413 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003414 if (DEBUG) Slog.d(TAG, "backup agent ("
3415 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003416 }
3417 mClearedPackages.add(pkg);
3418 } else {
3419 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3420 }
3421
3422 // All set; now set up the IPC and launch the agent
3423 setUpPipes();
3424 mAgent = bindToAgentSynchronous(mTargetApp,
3425 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3426 mAgentPackage = pkg;
3427 } catch (IOException e) {
3428 // fall through to error handling
3429 } catch (NameNotFoundException e) {
3430 // fall through to error handling
3431 }
3432
3433 if (mAgent == null) {
3434 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3435 okay = false;
3436 tearDownPipes();
3437 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3438 }
3439 }
3440
3441 // Sanity check: make sure we never give data to the wrong app. This
3442 // should never happen but a little paranoia here won't go amiss.
3443 if (okay && !pkg.equals(mAgentPackage)) {
3444 Slog.e(TAG, "Restoring data for " + pkg
3445 + " but agent is for " + mAgentPackage);
3446 okay = false;
3447 }
3448
3449 // At this point we have an agent ready to handle the full
3450 // restore data as well as a pipe for sending data to
3451 // that agent. Tell the agent to start reading from the
3452 // pipe.
3453 if (okay) {
3454 boolean agentSuccess = true;
3455 long toCopy = info.size;
3456 final int token = generateToken();
3457 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07003458 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate294b5122013-02-19 14:08:59 -08003459 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3460 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3461 + " : " + info.path);
3462 mObbConnection.restoreObbFile(pkg, mPipes[0],
3463 info.size, info.type, info.path, info.mode,
3464 info.mtime, token, mBackupManagerBinder);
Christopher Tate75a99702011-05-18 16:28:19 -07003465 } else {
Christopher Tate294b5122013-02-19 14:08:59 -08003466 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3467 + info.path);
3468 // fire up the app's agent listening on the socket. If
3469 // the agent is running in the system process we can't
3470 // just invoke it asynchronously, so we provide a thread
3471 // for it here.
3472 if (mTargetApp.processName.equals("system")) {
3473 Slog.d(TAG, "system process agent - spinning a thread");
3474 RestoreFileRunnable runner = new RestoreFileRunnable(
3475 mAgent, info, mPipes[0], token);
3476 new Thread(runner).start();
3477 } else {
3478 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3479 info.domain, info.path, info.mode, info.mtime,
3480 token, mBackupManagerBinder);
3481 }
Christopher Tate75a99702011-05-18 16:28:19 -07003482 }
3483 } catch (IOException e) {
3484 // couldn't dup the socket for a process-local restore
3485 Slog.d(TAG, "Couldn't establish restore");
3486 agentSuccess = false;
3487 okay = false;
3488 } catch (RemoteException e) {
Christopher Tate294b5122013-02-19 14:08:59 -08003489 // whoops, remote entity went away. We'll eat the content
Christopher Tate75a99702011-05-18 16:28:19 -07003490 // ourselves, then, and not copy it over.
3491 Slog.e(TAG, "Agent crashed during full restore");
3492 agentSuccess = false;
3493 okay = false;
3494 }
3495
3496 // Copy over the data if the agent is still good
3497 if (okay) {
3498 boolean pipeOkay = true;
3499 FileOutputStream pipe = new FileOutputStream(
3500 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003501 while (toCopy > 0) {
3502 int toRead = (toCopy > buffer.length)
3503 ? buffer.length : (int)toCopy;
3504 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003505 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003506 if (nRead <= 0) break;
3507 toCopy -= nRead;
3508
3509 // send it to the output pipe as long as things
3510 // are still good
3511 if (pipeOkay) {
3512 try {
3513 pipe.write(buffer, 0, nRead);
3514 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003515 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003516 pipeOkay = false;
3517 }
3518 }
3519 }
3520
3521 // done sending that file! Now we just need to consume
3522 // the delta from info.size to the end of block.
3523 skipTarPadding(info.size, instream);
3524
3525 // and now that we've sent it all, wait for the remote
3526 // side to acknowledge receipt
3527 agentSuccess = waitUntilOperationComplete(token);
3528 }
3529
3530 // okay, if the remote end failed at any point, deal with
3531 // it by ignoring the rest of the restore on it
3532 if (!agentSuccess) {
3533 mBackupHandler.removeMessages(MSG_TIMEOUT);
3534 tearDownPipes();
3535 tearDownAgent(mTargetApp);
3536 mAgent = null;
3537 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3538 }
3539 }
3540
3541 // Problems setting up the agent communication, or an already-
3542 // ignored package: skip to the next tar stream entry by
3543 // reading and discarding this file.
3544 if (!okay) {
3545 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3546 long bytesToConsume = (info.size + 511) & ~511;
3547 while (bytesToConsume > 0) {
3548 int toRead = (bytesToConsume > buffer.length)
3549 ? buffer.length : (int)bytesToConsume;
3550 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003551 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003552 if (nRead <= 0) break;
3553 bytesToConsume -= nRead;
3554 }
3555 }
3556 }
3557 }
3558 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003559 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003560 // treat as EOF
3561 info = null;
3562 }
3563
3564 return (info != null);
3565 }
3566
3567 void setUpPipes() throws IOException {
3568 mPipes = ParcelFileDescriptor.createPipe();
3569 }
3570
3571 void tearDownPipes() {
3572 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003573 try {
3574 mPipes[0].close();
3575 mPipes[0] = null;
3576 mPipes[1].close();
3577 mPipes[1] = null;
3578 } catch (IOException e) {
3579 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003580 }
3581 mPipes = null;
3582 }
3583 }
3584
3585 void tearDownAgent(ApplicationInfo app) {
3586 if (mAgent != null) {
3587 try {
3588 // unbind and tidy up even on timeout or failure, just in case
3589 mActivityManager.unbindBackupAgent(app);
3590
3591 // The agent was running with a stub Application object, so shut it down.
3592 // !!! We hardcode the confirmation UI's package name here rather than use a
3593 // manifest flag! TODO something less direct.
3594 if (app.uid != Process.SYSTEM_UID
3595 && !app.packageName.equals("com.android.backupconfirm")) {
3596 if (DEBUG) Slog.d(TAG, "Killing host process");
3597 mActivityManager.killApplicationProcess(app.processName, app.uid);
3598 } else {
3599 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3600 }
3601 } catch (RemoteException e) {
3602 Slog.d(TAG, "Lost app trying to shut down");
3603 }
3604 mAgent = null;
3605 }
3606 }
3607
3608 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3609 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003610 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003611 int mResult;
3612
3613 public void reset() {
3614 synchronized (mDone) {
3615 mDone.set(false);
3616 }
3617 }
3618
3619 public void waitForCompletion() {
3620 synchronized (mDone) {
3621 while (mDone.get() == false) {
3622 try {
3623 mDone.wait();
3624 } catch (InterruptedException e) { }
3625 }
3626 }
3627 }
3628
3629 int getResult() {
3630 return mResult;
3631 }
3632
3633 @Override
3634 public void packageInstalled(String packageName, int returnCode)
3635 throws RemoteException {
3636 synchronized (mDone) {
3637 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003638 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003639 mDone.set(true);
3640 mDone.notifyAll();
3641 }
3642 }
3643 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003644
3645 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3646 final AtomicBoolean mDone = new AtomicBoolean();
3647 int mResult;
3648
3649 public void reset() {
3650 synchronized (mDone) {
3651 mDone.set(false);
3652 }
3653 }
3654
3655 public void waitForCompletion() {
3656 synchronized (mDone) {
3657 while (mDone.get() == false) {
3658 try {
3659 mDone.wait();
3660 } catch (InterruptedException e) { }
3661 }
3662 }
3663 }
3664
3665 @Override
3666 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3667 synchronized (mDone) {
3668 mResult = returnCode;
3669 mDone.set(true);
3670 mDone.notifyAll();
3671 }
3672 }
3673 }
3674
Christopher Tate75a99702011-05-18 16:28:19 -07003675 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003676 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003677
3678 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3679 boolean okay = true;
3680
3681 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3682
3683 // The file content is an .apk file. Copy it out to a staging location and
3684 // attempt to install it.
3685 File apkFile = new File(mDataDir, info.packageName);
3686 try {
3687 FileOutputStream apkStream = new FileOutputStream(apkFile);
3688 byte[] buffer = new byte[32 * 1024];
3689 long size = info.size;
3690 while (size > 0) {
3691 long toRead = (buffer.length < size) ? buffer.length : size;
3692 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003693 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003694 apkStream.write(buffer, 0, didRead);
3695 size -= didRead;
3696 }
3697 apkStream.close();
3698
3699 // make sure the installer can read it
3700 apkFile.setReadable(true, false);
3701
3702 // Now install it
3703 Uri packageUri = Uri.fromFile(apkFile);
3704 mInstallObserver.reset();
3705 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003706 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3707 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003708 mInstallObserver.waitForCompletion();
3709
3710 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3711 // The only time we continue to accept install of data even if the
3712 // apk install failed is if we had already determined that we could
3713 // accept the data regardless.
3714 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3715 okay = false;
3716 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003717 } else {
3718 // Okay, the install succeeded. Make sure it was the right app.
3719 boolean uninstall = false;
3720 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3721 Slog.w(TAG, "Restore stream claimed to include apk for "
3722 + info.packageName + " but apk was really "
3723 + mInstallObserver.mPackageName);
3724 // delete the package we just put in place; it might be fraudulent
3725 okay = false;
3726 uninstall = true;
3727 } else {
3728 try {
3729 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3730 PackageManager.GET_SIGNATURES);
3731 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3732 Slog.w(TAG, "Restore stream contains apk of package "
3733 + info.packageName + " but it disallows backup/restore");
3734 okay = false;
3735 } else {
3736 // So far so good -- do the signatures match the manifest?
3737 Signature[] sigs = mManifestSignatures.get(info.packageName);
3738 if (!signaturesMatch(sigs, pkg)) {
3739 Slog.w(TAG, "Installed app " + info.packageName
3740 + " signatures do not match restore manifest");
3741 okay = false;
3742 uninstall = true;
3743 }
3744 }
3745 } catch (NameNotFoundException e) {
3746 Slog.w(TAG, "Install of package " + info.packageName
3747 + " succeeded but now not found");
3748 okay = false;
3749 }
3750 }
3751
3752 // If we're not okay at this point, we need to delete the package
3753 // that we just installed.
3754 if (uninstall) {
3755 mDeleteObserver.reset();
3756 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3757 mDeleteObserver, 0);
3758 mDeleteObserver.waitForCompletion();
3759 }
Christopher Tate75a99702011-05-18 16:28:19 -07003760 }
3761 } catch (IOException e) {
3762 Slog.e(TAG, "Unable to transcribe restored apk for install");
3763 okay = false;
3764 } finally {
3765 apkFile.delete();
3766 }
3767
3768 return okay;
3769 }
3770
3771 // Given an actual file content size, consume the post-content padding mandated
3772 // by the tar format.
3773 void skipTarPadding(long size, InputStream instream) throws IOException {
3774 long partial = (size + 512) % 512;
3775 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003776 final int needed = 512 - (int)partial;
3777 byte[] buffer = new byte[needed];
3778 if (readExactly(instream, buffer, 0, needed) == needed) {
3779 mBytes += needed;
3780 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003781 }
3782 }
3783
3784 // Returns a policy constant; takes a buffer arg to reduce memory churn
3785 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3786 throws IOException {
3787 // Fail on suspiciously large manifest files
3788 if (info.size > 64 * 1024) {
3789 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3790 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003791
Christopher Tate75a99702011-05-18 16:28:19 -07003792 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003793 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3794 mBytes += info.size;
3795 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003796
3797 RestorePolicy policy = RestorePolicy.IGNORE;
3798 String[] str = new String[1];
3799 int offset = 0;
3800
3801 try {
3802 offset = extractLine(buffer, offset, str);
3803 int version = Integer.parseInt(str[0]);
3804 if (version == BACKUP_MANIFEST_VERSION) {
3805 offset = extractLine(buffer, offset, str);
3806 String manifestPackage = str[0];
3807 // TODO: handle <original-package>
3808 if (manifestPackage.equals(info.packageName)) {
3809 offset = extractLine(buffer, offset, str);
3810 version = Integer.parseInt(str[0]); // app version
3811 offset = extractLine(buffer, offset, str);
3812 int platformVersion = Integer.parseInt(str[0]);
3813 offset = extractLine(buffer, offset, str);
3814 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3815 offset = extractLine(buffer, offset, str);
3816 boolean hasApk = str[0].equals("1");
3817 offset = extractLine(buffer, offset, str);
3818 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003819 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003820 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003821 for (int i = 0; i < numSigs; i++) {
3822 offset = extractLine(buffer, offset, str);
3823 sigs[i] = new Signature(str[0]);
3824 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003825 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003826
3827 // Okay, got the manifest info we need...
3828 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003829 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3830 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003831 // Fall through to IGNORE if the app explicitly disallows backup
3832 final int flags = pkgInfo.applicationInfo.flags;
3833 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003834 // Restore system-uid-space packages only if they have
3835 // defined a custom backup agent
3836 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3837 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3838 // Verify signatures against any installed version; if they
3839 // don't match, then we fall though and ignore the data. The
3840 // signatureMatch() method explicitly ignores the signature
3841 // check for packages installed on the system partition, because
3842 // such packages are signed with the platform cert instead of
3843 // the app developer's cert, so they're different on every
3844 // device.
3845 if (signaturesMatch(sigs, pkgInfo)) {
3846 if (pkgInfo.versionCode >= version) {
3847 Slog.i(TAG, "Sig + version match; taking data");
3848 policy = RestorePolicy.ACCEPT;
3849 } else {
3850 // The data is from a newer version of the app than
3851 // is presently installed. That means we can only
3852 // use it if the matching apk is also supplied.
3853 Slog.d(TAG, "Data version " + version
3854 + " is newer than installed version "
3855 + pkgInfo.versionCode + " - requiring apk");
3856 policy = RestorePolicy.ACCEPT_IF_APK;
3857 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003858 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003859 Slog.w(TAG, "Restore manifest signatures do not match "
3860 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003861 }
Christopher Tate75a99702011-05-18 16:28:19 -07003862 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003863 Slog.w(TAG, "Package " + info.packageName
3864 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003865 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003866 } else {
3867 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3868 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003869 }
3870 } catch (NameNotFoundException e) {
3871 // Okay, the target app isn't installed. We can process
3872 // the restore properly only if the dataset provides the
3873 // apk file and we can successfully install it.
3874 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3875 + " not installed; requiring apk in dataset");
3876 policy = RestorePolicy.ACCEPT_IF_APK;
3877 }
3878
3879 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3880 Slog.i(TAG, "Cannot restore package " + info.packageName
3881 + " without the matching .apk");
3882 }
3883 } else {
3884 Slog.i(TAG, "Missing signature on backed-up package "
3885 + info.packageName);
3886 }
3887 } else {
3888 Slog.i(TAG, "Expected package " + info.packageName
3889 + " but restore manifest claims " + manifestPackage);
3890 }
3891 } else {
3892 Slog.i(TAG, "Unknown restore manifest version " + version
3893 + " for package " + info.packageName);
3894 }
3895 } catch (NumberFormatException e) {
3896 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003897 } catch (IllegalArgumentException e) {
3898 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003899 }
3900
3901 return policy;
3902 }
3903
3904 // Builds a line from a byte buffer starting at 'offset', and returns
3905 // the index of the next unconsumed data in the buffer.
3906 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3907 final int end = buffer.length;
3908 if (offset >= end) throw new IOException("Incomplete data");
3909
3910 int pos;
3911 for (pos = offset; pos < end; pos++) {
3912 byte c = buffer[pos];
3913 // at LF we declare end of line, and return the next char as the
3914 // starting point for the next time through
3915 if (c == '\n') {
3916 break;
3917 }
3918 }
3919 outStr[0] = new String(buffer, offset, pos - offset);
3920 pos++; // may be pointing an extra byte past the end but that's okay
3921 return pos;
3922 }
3923
3924 void dumpFileMetadata(FileMetadata info) {
3925 if (DEBUG) {
3926 StringBuilder b = new StringBuilder(128);
3927
3928 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003929 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003930 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3931 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3932 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3933 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3934 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3935 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3936 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3937 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3938 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3939 b.append(String.format(" %9d ", info.size));
3940
3941 Date stamp = new Date(info.mtime);
Elliott Hughes64a277d82013-03-18 17:47:22 -07003942 b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
Christopher Tate75a99702011-05-18 16:28:19 -07003943
3944 b.append(info.packageName);
3945 b.append(" :: ");
3946 b.append(info.domain);
3947 b.append(" :: ");
3948 b.append(info.path);
3949
3950 Slog.i(TAG, b.toString());
3951 }
3952 }
3953 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3954 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3955 byte[] block = new byte[512];
3956 FileMetadata info = null;
3957
3958 boolean gotHeader = readTarHeader(instream, block);
3959 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003960 try {
3961 // okay, presume we're okay, and extract the various metadata
3962 info = new FileMetadata();
3963 info.size = extractRadix(block, 124, 12, 8);
3964 info.mtime = extractRadix(block, 136, 12, 8);
3965 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003966
Christopher Tate2efd2db2011-07-19 16:32:49 -07003967 info.path = extractString(block, 345, 155); // prefix
3968 String path = extractString(block, 0, 100);
3969 if (path.length() > 0) {
3970 if (info.path.length() > 0) info.path += '/';
3971 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003972 }
Christopher Tate75a99702011-05-18 16:28:19 -07003973
Christopher Tate2efd2db2011-07-19 16:32:49 -07003974 // tar link indicator field: 1 byte at offset 156 in the header.
3975 int typeChar = block[156];
3976 if (typeChar == 'x') {
3977 // pax extended header, so we need to read that
3978 gotHeader = readPaxExtendedHeader(instream, info);
3979 if (gotHeader) {
3980 // and after a pax extended header comes another real header -- read
3981 // that to find the real file type
3982 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003983 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003984 if (!gotHeader) throw new IOException("Bad or missing pax header");
3985
3986 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003987 }
Christopher Tate75a99702011-05-18 16:28:19 -07003988
Christopher Tate2efd2db2011-07-19 16:32:49 -07003989 switch (typeChar) {
3990 case '0': info.type = BackupAgent.TYPE_FILE; break;
3991 case '5': {
3992 info.type = BackupAgent.TYPE_DIRECTORY;
3993 if (info.size != 0) {
3994 Slog.w(TAG, "Directory entry with nonzero size in header");
3995 info.size = 0;
3996 }
3997 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003998 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003999 case 0: {
4000 // presume EOF
4001 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
4002 return null;
4003 }
4004 default: {
4005 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
4006 throw new IOException("Unknown entity type " + typeChar);
4007 }
Christopher Tate75a99702011-05-18 16:28:19 -07004008 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004009
4010 // Parse out the path
4011 //
4012 // first: apps/shared/unrecognized
4013 if (FullBackup.SHARED_PREFIX.regionMatches(0,
4014 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4015 // File in shared storage. !!! TODO: implement this.
4016 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08004017 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004018 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4019 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4020 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4021 info.path, 0, FullBackup.APPS_PREFIX.length())) {
4022 // App content! Parse out the package name and domain
4023
4024 // strip the apps/ prefix
4025 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4026
4027 // extract the package name
4028 int slash = info.path.indexOf('/');
4029 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4030 info.packageName = info.path.substring(0, slash);
4031 info.path = info.path.substring(slash+1);
4032
4033 // if it's a manifest we're done, otherwise parse out the domains
4034 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4035 slash = info.path.indexOf('/');
4036 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4037 info.domain = info.path.substring(0, slash);
Christopher Tate2efd2db2011-07-19 16:32:49 -07004038 info.path = info.path.substring(slash + 1);
4039 }
4040 }
4041 } catch (IOException e) {
4042 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07004043 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07004044 HEXLOG(block);
4045 }
4046 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07004047 }
4048 }
4049 return info;
4050 }
4051
Christopher Tate2efd2db2011-07-19 16:32:49 -07004052 private void HEXLOG(byte[] block) {
4053 int offset = 0;
4054 int todo = block.length;
4055 StringBuilder buf = new StringBuilder(64);
4056 while (todo > 0) {
4057 buf.append(String.format("%04x ", offset));
4058 int numThisLine = (todo > 16) ? 16 : todo;
4059 for (int i = 0; i < numThisLine; i++) {
4060 buf.append(String.format("%02x ", block[offset+i]));
4061 }
4062 Slog.i("hexdump", buf.toString());
4063 buf.setLength(0);
4064 todo -= numThisLine;
4065 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07004066 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004067 }
4068
Christopher Tate6853fcf2011-08-10 17:52:21 -07004069 // Read exactly the given number of bytes into a buffer at the stated offset.
4070 // Returns false if EOF is encountered before the requested number of bytes
4071 // could be read.
4072 int readExactly(InputStream in, byte[] buffer, int offset, int size)
4073 throws IOException {
4074 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4075
4076 int soFar = 0;
4077 while (soFar < size) {
4078 int nRead = in.read(buffer, offset + soFar, size - soFar);
4079 if (nRead <= 0) {
4080 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4081 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004082 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004083 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004084 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004085 return soFar;
4086 }
4087
4088 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4089 final int got = readExactly(instream, block, 0, 512);
4090 if (got == 0) return false; // Clean EOF
4091 if (got < 512) throw new IOException("Unable to read full block header");
4092 mBytes += 512;
4093 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07004094 }
4095
4096 // overwrites 'info' fields based on the pax extended header
4097 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4098 throws IOException {
4099 // We should never see a pax extended header larger than this
4100 if (info.size > 32*1024) {
4101 Slog.w(TAG, "Suspiciously large pax header size " + info.size
4102 + " - aborting");
4103 throw new IOException("Sanity failure: pax header size " + info.size);
4104 }
4105
4106 // read whole blocks, not just the content size
4107 int numBlocks = (int)((info.size + 511) >> 9);
4108 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07004109 if (readExactly(instream, data, 0, data.length) < data.length) {
4110 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07004111 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004112 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07004113
4114 final int contentSize = (int) info.size;
4115 int offset = 0;
4116 do {
4117 // extract the line at 'offset'
4118 int eol = offset+1;
4119 while (eol < contentSize && data[eol] != ' ') eol++;
4120 if (eol >= contentSize) {
4121 // error: we just hit EOD looking for the end of the size field
4122 throw new IOException("Invalid pax data");
4123 }
4124 // eol points to the space between the count and the key
4125 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4126 int key = eol + 1; // start of key=value
4127 eol = offset + linelen - 1; // trailing LF
4128 int value;
4129 for (value = key+1; data[value] != '=' && value <= eol; value++);
4130 if (value > eol) {
4131 throw new IOException("Invalid pax declaration");
4132 }
4133
4134 // pax requires that key/value strings be in UTF-8
4135 String keyStr = new String(data, key, value-key, "UTF-8");
4136 // -1 to strip the trailing LF
4137 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4138
4139 if ("path".equals(keyStr)) {
4140 info.path = valStr;
4141 } else if ("size".equals(keyStr)) {
4142 info.size = Long.parseLong(valStr);
4143 } else {
4144 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4145 }
4146
4147 offset += linelen;
4148 } while (offset < contentSize);
4149
4150 return true;
4151 }
4152
4153 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4154 throws IOException {
4155 long value = 0;
4156 final int end = offset + maxChars;
4157 for (int i = offset; i < end; i++) {
4158 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004159 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004160 if (b == 0 || b == ' ') break;
4161 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004162 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004163 }
4164 value = radix * value + (b - '0');
4165 }
4166 return value;
4167 }
4168
4169 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4170 final int end = offset + maxChars;
4171 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004172 // tar string fields terminate early with a NUL
4173 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004174 return new String(data, offset, eos-offset, "US-ASCII");
4175 }
4176
4177 void sendStartRestore() {
4178 if (mObserver != null) {
4179 try {
4180 mObserver.onStartRestore();
4181 } catch (RemoteException e) {
4182 Slog.w(TAG, "full restore observer went away: startRestore");
4183 mObserver = null;
4184 }
4185 }
4186 }
4187
4188 void sendOnRestorePackage(String name) {
4189 if (mObserver != null) {
4190 try {
4191 // TODO: use a more user-friendly name string
4192 mObserver.onRestorePackage(name);
4193 } catch (RemoteException e) {
4194 Slog.w(TAG, "full restore observer went away: restorePackage");
4195 mObserver = null;
4196 }
4197 }
4198 }
4199
4200 void sendEndRestore() {
4201 if (mObserver != null) {
4202 try {
4203 mObserver.onEndRestore();
4204 } catch (RemoteException e) {
4205 Slog.w(TAG, "full restore observer went away: endRestore");
4206 mObserver = null;
4207 }
4208 }
4209 }
4210 }
4211
Christopher Tatedf01dea2009-06-09 20:45:02 -07004212 // ----- Restore handling -----
4213
Christopher Tate78dd4a72009-11-04 11:49:08 -08004214 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4215 // If the target resides on the system partition, we allow it to restore
4216 // data from the like-named package in a restore set even if the signatures
4217 // do not match. (Unlike general applications, those flashed to the system
4218 // partition will be signed with the device's platform certificate, so on
4219 // different phones the same system app will have different signatures.)
4220 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004221 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004222 return true;
4223 }
4224
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004225 // Allow unsigned apps, but not signed on one device and unsigned on the other
4226 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004227 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004228 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004229 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004230 if ((storedSigs == null || storedSigs.length == 0)
4231 && (deviceSigs == null || deviceSigs.length == 0)) {
4232 return true;
4233 }
4234 if (storedSigs == null || deviceSigs == null) {
4235 return false;
4236 }
4237
Christopher Tateabce4e82009-06-18 18:35:32 -07004238 // !!! TODO: this demands that every stored signature match one
4239 // that is present on device, and does not demand the converse.
4240 // Is this this right policy?
4241 int nStored = storedSigs.length;
4242 int nDevice = deviceSigs.length;
4243
4244 for (int i=0; i < nStored; i++) {
4245 boolean match = false;
4246 for (int j=0; j < nDevice; j++) {
4247 if (storedSigs[i].equals(deviceSigs[j])) {
4248 match = true;
4249 break;
4250 }
4251 }
4252 if (!match) {
4253 return false;
4254 }
4255 }
4256 return true;
4257 }
4258
Christopher Tate2982d062011-09-06 20:35:24 -07004259 enum RestoreState {
4260 INITIAL,
4261 DOWNLOAD_DATA,
4262 PM_METADATA,
4263 RUNNING_QUEUE,
4264 FINAL
4265 }
4266
4267 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004268 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004269 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004270 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004271 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004272 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004273 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004274 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004275 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004276 private long mStartRealtime;
4277 private PackageManagerBackupAgent mPmAgent;
4278 private List<PackageInfo> mAgentPackages;
4279 private ArrayList<PackageInfo> mRestorePackages;
4280 private RestoreState mCurrentState;
4281 private int mCount;
4282 private boolean mFinished;
4283 private int mStatus;
4284 private File mBackupDataName;
4285 private File mNewStateName;
4286 private File mSavedStateName;
4287 private ParcelFileDescriptor mBackupData;
4288 private ParcelFileDescriptor mNewState;
4289 private PackageInfo mCurrentPackage;
4290
Christopher Tatedf01dea2009-06-09 20:45:02 -07004291
Christopher Tate5cbbf562009-06-22 16:44:51 -07004292 class RestoreRequest {
4293 public PackageInfo app;
4294 public int storedAppVersion;
4295
4296 RestoreRequest(PackageInfo _app, int _version) {
4297 app = _app;
4298 storedAppVersion = _version;
4299 }
4300 }
4301
Christopher Tate44a27902010-01-27 17:15:49 -08004302 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004303 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004304 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004305 mCurrentState = RestoreState.INITIAL;
4306 mFinished = false;
4307 mPmAgent = null;
4308
Christopher Tatedf01dea2009-06-09 20:45:02 -07004309 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004310 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004311 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004312 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004313 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004314 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004315
Christopher Tate284f1bb2011-07-07 14:31:18 -07004316 if (filterSet != null) {
4317 mFilterSet = new HashSet<String>();
4318 for (String pkg : filterSet) {
4319 mFilterSet.add(pkg);
4320 }
4321 } else {
4322 mFilterSet = null;
4323 }
4324
Christopher Tate5cb400b2009-06-25 16:03:14 -07004325 try {
4326 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4327 } catch (RemoteException e) {
4328 // can't happen; the transport is local
4329 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004330 }
4331
Christopher Tate2982d062011-09-06 20:35:24 -07004332 // Execute one tick of whatever state machine the task implements
4333 @Override
4334 public void execute() {
4335 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4336 switch (mCurrentState) {
4337 case INITIAL:
4338 beginRestore();
4339 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004340
Christopher Tate2982d062011-09-06 20:35:24 -07004341 case DOWNLOAD_DATA:
4342 downloadRestoreData();
4343 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004344
Christopher Tate2982d062011-09-06 20:35:24 -07004345 case PM_METADATA:
4346 restorePmMetadata();
4347 break;
4348
4349 case RUNNING_QUEUE:
4350 restoreNextAgent();
4351 break;
4352
4353 case FINAL:
4354 if (!mFinished) finalizeRestore();
4355 else {
4356 Slog.e(TAG, "Duplicate finish");
4357 }
4358 mFinished = true;
4359 break;
4360 }
4361 }
4362
4363 // Initialize and set up for the PM metadata restore, which comes first
4364 void beginRestore() {
4365 // Don't account time doing the restore as inactivity of the app
4366 // that has opened a restore session.
4367 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4368
4369 // Assume error until we successfully init everything
4370 mStatus = BackupConstants.TRANSPORT_ERROR;
4371
Christopher Tatedf01dea2009-06-09 20:45:02 -07004372 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004373 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004374 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004375
Dan Egnorefe52642009-06-24 00:16:33 -07004376 // Get the list of all packages which have backup enabled.
4377 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004378 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004379 PackageInfo omPackage = new PackageInfo();
4380 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004381 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004382
Christopher Tate2982d062011-09-06 20:35:24 -07004383 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004384 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004385 // if there's a filter set, strip out anything that isn't
4386 // present before proceeding
4387 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004388 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4389 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004390 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004391 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004392 }
4393 }
Christopher Tate2982d062011-09-06 20:35:24 -07004394 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004395 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004396 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004397 Slog.i(TAG, " " + p);
4398 }
4399 }
4400 }
Christopher Tate2982d062011-09-06 20:35:24 -07004401 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004402 } else {
4403 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004404 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004405 }
Dan Egnorefe52642009-06-24 00:16:33 -07004406
Christopher Tate7d562ec2009-06-25 18:03:43 -07004407 // let the observer know that we're running
4408 if (mObserver != null) {
4409 try {
4410 // !!! TODO: get an actual count from the transport after
4411 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004412 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004413 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004414 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004415 mObserver = null;
4416 }
4417 }
Christopher Tate2982d062011-09-06 20:35:24 -07004418 } catch (RemoteException e) {
4419 // Something has gone catastrophically wrong with the transport
4420 Slog.e(TAG, "Error communicating with transport for restore");
4421 executeNextState(RestoreState.FINAL);
4422 return;
4423 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004424
Christopher Tate2982d062011-09-06 20:35:24 -07004425 mStatus = BackupConstants.TRANSPORT_OK;
4426 executeNextState(RestoreState.DOWNLOAD_DATA);
4427 }
4428
4429 void downloadRestoreData() {
4430 // Note that the download phase can be very time consuming, but we're executing
4431 // it inline here on the looper. This is "okay" because it is not calling out to
4432 // third party code; the transport is "trusted," and so we assume it is being a
4433 // good citizen and timing out etc when appropriate.
4434 //
4435 // TODO: when appropriate, move the download off the looper and rearrange the
4436 // error handling around that.
4437 try {
4438 mStatus = mTransport.startRestore(mToken,
4439 mRestorePackages.toArray(new PackageInfo[0]));
4440 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004441 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004442 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004443 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004444 return;
4445 }
Christopher Tate2982d062011-09-06 20:35:24 -07004446 } catch (RemoteException e) {
4447 Slog.e(TAG, "Error communicating with transport for restore");
4448 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4449 mStatus = BackupConstants.TRANSPORT_ERROR;
4450 executeNextState(RestoreState.FINAL);
4451 return;
4452 }
Dan Egnorefe52642009-06-24 00:16:33 -07004453
Christopher Tate2982d062011-09-06 20:35:24 -07004454 // Successful download of the data to be parceled out to the apps, so off we go.
4455 executeNextState(RestoreState.PM_METADATA);
4456 }
4457
4458 void restorePmMetadata() {
4459 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004460 String packageName = mTransport.nextRestorePackage();
4461 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004462 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004463 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004464 mStatus = BackupConstants.TRANSPORT_ERROR;
4465 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004466 return;
4467 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004468 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004469 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004470 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004471 mStatus = BackupConstants.TRANSPORT_OK;
4472 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004473 return;
4474 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004475 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004476 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004477 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004478 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004479 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004480 return;
4481 }
4482
4483 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004484 PackageInfo omPackage = new PackageInfo();
4485 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4486 mPmAgent = new PackageManagerBackupAgent(
4487 mPackageManager, mAgentPackages);
4488 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004489 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004490 // The PM agent called operationComplete() already, because our invocation
4491 // of it is process-local and therefore synchronous. That means that a
4492 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4493 // proceed with running the queue do we remove that pending message and
4494 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004495
Christopher Tate8c032472009-07-02 14:28:47 -07004496 // Verify that the backup set includes metadata. If not, we can't do
4497 // signature/version verification etc, so we simply do not proceed with
4498 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004499 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004500 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004501 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004502 "Package manager restore metadata missing");
4503 mStatus = BackupConstants.TRANSPORT_ERROR;
4504 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4505 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004506 return;
4507 }
Christopher Tate2982d062011-09-06 20:35:24 -07004508 } catch (RemoteException e) {
4509 Slog.e(TAG, "Error communicating with transport for restore");
4510 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4511 mStatus = BackupConstants.TRANSPORT_ERROR;
4512 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4513 executeNextState(RestoreState.FINAL);
4514 return;
4515 }
Christopher Tate8c032472009-07-02 14:28:47 -07004516
Christopher Tate2982d062011-09-06 20:35:24 -07004517 // Metadata is intact, so we can now run the restore queue. If we get here,
4518 // we have already enqueued the necessary next-step message on the looper.
4519 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004520
Christopher Tate2982d062011-09-06 20:35:24 -07004521 void restoreNextAgent() {
4522 try {
4523 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004524
Christopher Tate2982d062011-09-06 20:35:24 -07004525 if (packageName == null) {
4526 Slog.e(TAG, "Error getting next restore package");
4527 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4528 executeNextState(RestoreState.FINAL);
4529 return;
4530 } else if (packageName.equals("")) {
4531 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4532 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4533 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4534 executeNextState(RestoreState.FINAL);
4535 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004536 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004537
4538 if (mObserver != null) {
4539 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004540 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004541 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004542 Slog.d(TAG, "Restore observer died in onUpdate");
4543 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004544 }
4545 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004546
Christopher Tate2982d062011-09-06 20:35:24 -07004547 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4548 if (metaInfo == null) {
4549 Slog.e(TAG, "Missing metadata for " + packageName);
4550 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4551 "Package metadata missing");
4552 executeNextState(RestoreState.RUNNING_QUEUE);
4553 return;
Christopher Tate84725812010-02-04 15:52:40 -08004554 }
4555
Christopher Tate2982d062011-09-06 20:35:24 -07004556 PackageInfo packageInfo;
4557 try {
4558 int flags = PackageManager.GET_SIGNATURES;
4559 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4560 } catch (NameNotFoundException e) {
4561 Slog.e(TAG, "Invalid package restoring data", e);
4562 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4563 "Package missing on device");
4564 executeNextState(RestoreState.RUNNING_QUEUE);
4565 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004566 }
4567
Christopher Tatee7287a02012-09-07 18:32:12 -07004568 if (packageInfo.applicationInfo.backupAgentName == null
4569 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4570 if (DEBUG) {
4571 Slog.i(TAG, "Data exists for package " + packageName
4572 + " but app has no agent; skipping");
4573 }
4574 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4575 "Package has no agent");
4576 executeNextState(RestoreState.RUNNING_QUEUE);
4577 return;
4578 }
4579
Christopher Tate2982d062011-09-06 20:35:24 -07004580 if (metaInfo.versionCode > packageInfo.versionCode) {
4581 // Data is from a "newer" version of the app than we have currently
4582 // installed. If the app has not declared that it is prepared to
4583 // handle this case, we do not attempt the restore.
4584 if ((packageInfo.applicationInfo.flags
4585 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4586 String message = "Version " + metaInfo.versionCode
4587 + " > installed version " + packageInfo.versionCode;
4588 Slog.w(TAG, "Package " + packageName + ": " + message);
4589 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4590 packageName, message);
4591 executeNextState(RestoreState.RUNNING_QUEUE);
4592 return;
4593 } else {
4594 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4595 + " > installed " + packageInfo.versionCode
4596 + " but restoreAnyVersion");
4597 }
4598 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004599
Christopher Tate2982d062011-09-06 20:35:24 -07004600 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4601 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4602 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4603 "Signature mismatch");
4604 executeNextState(RestoreState.RUNNING_QUEUE);
4605 return;
4606 }
4607
4608 if (DEBUG) Slog.v(TAG, "Package " + packageName
4609 + " restore version [" + metaInfo.versionCode
4610 + "] is compatible with installed version ["
4611 + packageInfo.versionCode + "]");
4612
4613 // Then set up and bind the agent
4614 IBackupAgent agent = bindToAgentSynchronous(
4615 packageInfo.applicationInfo,
4616 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4617 if (agent == null) {
4618 Slog.w(TAG, "Can't find backup agent for " + packageName);
4619 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4620 "Restore agent missing");
4621 executeNextState(RestoreState.RUNNING_QUEUE);
4622 return;
4623 }
4624
4625 // And then finally start the restore on this agent
4626 try {
4627 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4628 ++mCount;
4629 } catch (Exception e) {
4630 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4631 agentErrorCleanup();
4632 executeNextState(RestoreState.RUNNING_QUEUE);
4633 }
4634 } catch (RemoteException e) {
4635 Slog.e(TAG, "Unable to fetch restore data from transport");
4636 mStatus = BackupConstants.TRANSPORT_ERROR;
4637 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004638 }
4639 }
4640
Christopher Tate2982d062011-09-06 20:35:24 -07004641 void finalizeRestore() {
4642 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4643
4644 try {
4645 mTransport.finishRestore();
4646 } catch (RemoteException e) {
4647 Slog.e(TAG, "Error finishing restore", e);
4648 }
4649
4650 if (mObserver != null) {
4651 try {
4652 mObserver.restoreFinished(mStatus);
4653 } catch (RemoteException e) {
4654 Slog.d(TAG, "Restore observer died at restoreFinished");
4655 }
4656 }
4657
4658 // If this was a restoreAll operation, record that this was our
4659 // ancestral dataset, as well as the set of apps that are possibly
4660 // restoreable from the dataset
4661 if (mTargetPackage == null && mPmAgent != null) {
4662 mAncestralPackages = mPmAgent.getRestoredPackages();
4663 mAncestralToken = mToken;
4664 writeRestoreTokens();
4665 }
4666
4667 // We must under all circumstances tell the Package Manager to
4668 // proceed with install notifications if it's waiting for us.
4669 if (mPmToken > 0) {
4670 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4671 try {
4672 mPackageManagerBinder.finishPackageInstall(mPmToken);
4673 } catch (RemoteException e) { /* can't happen */ }
4674 }
4675
4676 // Furthermore we need to reset the session timeout clock
4677 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4678 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4679 TIMEOUT_RESTORE_INTERVAL);
4680
4681 // done; we can finally release the wakelock
4682 Slog.i(TAG, "Restore complete.");
4683 mWakelock.release();
4684 }
4685
4686 // Call asynchronously into the app, passing it the restore data. The next step
4687 // after this is always a callback, either operationComplete() or handleTimeout().
4688 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004689 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004690 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004691 final String packageName = app.packageName;
4692
Christopher Tate2982d062011-09-06 20:35:24 -07004693 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004694
Christopher Tatec7b31e32009-06-10 15:49:30 -07004695 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004696 mBackupDataName = new File(mDataDir, packageName + ".restore");
4697 mNewStateName = new File(mStateDir, packageName + ".new");
4698 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004699
Christopher Tate4a627c72011-04-01 14:43:32 -07004700 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004701 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004702 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004703 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004704 ParcelFileDescriptor.MODE_READ_WRITE |
4705 ParcelFileDescriptor.MODE_CREATE |
4706 ParcelFileDescriptor.MODE_TRUNCATE);
4707
rpcraigebab0ae2012-12-04 09:37:23 -05004708 if (!SELinux.restorecon(mBackupDataName)) {
4709 Slog.e(TAG, "SElinux restorecon failed for " + mBackupDataName);
4710 }
4711
Christopher Tate2982d062011-09-06 20:35:24 -07004712 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004713 // Transport-level failure, so we wind everything up and
4714 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004715 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004716 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004717 mBackupData.close();
4718 mBackupDataName.delete();
4719 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004720 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004721 }
4722
4723 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004724 mBackupData.close();
4725 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004726 ParcelFileDescriptor.MODE_READ_ONLY);
4727
Christopher Tate2982d062011-09-06 20:35:24 -07004728 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004729 ParcelFileDescriptor.MODE_READ_WRITE |
4730 ParcelFileDescriptor.MODE_CREATE |
4731 ParcelFileDescriptor.MODE_TRUNCATE);
4732
Christopher Tate44a27902010-01-27 17:15:49 -08004733 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004734 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4735 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004736 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004737 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004738 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004739 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004740
Christopher Tate2982d062011-09-06 20:35:24 -07004741 // After a restore failure we go back to running the queue. If there
4742 // are no more packages to be restored that will be handled by the
4743 // next step.
4744 executeNextState(RestoreState.RUNNING_QUEUE);
4745 }
4746 }
Chris Tate249345b2010-10-29 12:57:04 -07004747
Christopher Tate2982d062011-09-06 20:35:24 -07004748 void agentErrorCleanup() {
4749 // If the agent fails restore, it might have put the app's data
4750 // into an incoherent state. For consistency we wipe its data
4751 // again in this case before continuing with normal teardown
4752 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4753 agentCleanup();
4754 }
4755
4756 void agentCleanup() {
4757 mBackupDataName.delete();
4758 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4759 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4760 mBackupData = mNewState = null;
4761
4762 // if everything went okay, remember the recorded state now
4763 //
4764 // !!! TODO: the restored data should be migrated on the server
4765 // side into the current dataset. In that case the new state file
4766 // we just created would reflect the data already extant in the
4767 // backend, so there'd be nothing more to do. Until that happens,
4768 // however, we need to make sure that we record the data to the
4769 // current backend dataset. (Yes, this means shipping the data over
4770 // the wire in both directions. That's bad, but consistency comes
4771 // first, then efficiency.) Once we introduce server-side data
4772 // migration to the newly-restored device's dataset, we will change
4773 // the following from a discard of the newly-written state to the
4774 // "correct" operation of renaming into the canonical state blob.
4775 mNewStateName.delete(); // TODO: remove; see above comment
4776 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4777
4778 // If this wasn't the PM pseudopackage, tear down the agent side
4779 if (mCurrentPackage.applicationInfo != null) {
4780 // unbind and tidy up even on timeout or failure
4781 try {
4782 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4783
4784 // The agent was probably running with a stub Application object,
4785 // which isn't a valid run mode for the main app logic. Shut
4786 // down the app so that next time it's launched, it gets the
4787 // usual full initialization. Note that this is only done for
4788 // full-system restores: when a single app has requested a restore,
4789 // it is explicitly not killed following that operation.
4790 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4791 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4792 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4793 + mCurrentPackage.applicationInfo.processName);
4794 mActivityManager.killApplicationProcess(
4795 mCurrentPackage.applicationInfo.processName,
4796 mCurrentPackage.applicationInfo.uid);
4797 }
4798 } catch (RemoteException e) {
4799 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004800 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004801 }
Christopher Tate2982d062011-09-06 20:35:24 -07004802
4803 // The caller is responsible for reestablishing the state machine; our
4804 // responsibility here is to clear the decks for whatever comes next.
4805 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4806 synchronized (mCurrentOpLock) {
4807 mCurrentOperations.clear();
4808 }
4809 }
4810
4811 // A call to agent.doRestore() has been positively acknowledged as complete
4812 @Override
4813 public void operationComplete() {
4814 int size = (int) mBackupDataName.length();
4815 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4816 // Just go back to running the restore queue
4817 agentCleanup();
4818
4819 executeNextState(RestoreState.RUNNING_QUEUE);
4820 }
4821
4822 // A call to agent.doRestore() has timed out
4823 @Override
4824 public void handleTimeout() {
4825 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4826 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4827 mCurrentPackage.packageName, "restore timeout");
4828 // Handle like an agent that threw on invocation: wipe it and go on to the next
4829 agentErrorCleanup();
4830 executeNextState(RestoreState.RUNNING_QUEUE);
4831 }
4832
4833 void executeNextState(RestoreState nextState) {
4834 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4835 + this + " nextState=" + nextState);
4836 mCurrentState = nextState;
4837 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4838 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004839 }
4840 }
4841
Christopher Tate44a27902010-01-27 17:15:49 -08004842 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004843 IBackupTransport mTransport;
4844 PackageInfo mPackage;
4845
Christopher Tate44a27902010-01-27 17:15:49 -08004846 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004847 mTransport = transport;
4848 mPackage = packageInfo;
4849 }
4850
Christopher Tateee0e78a2009-07-02 11:17:03 -07004851 public void run() {
4852 try {
4853 // Clear the on-device backup state to ensure a full backup next time
4854 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4855 File stateFile = new File(stateDir, mPackage.packageName);
4856 stateFile.delete();
4857
4858 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004859 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004860 mTransport.clearBackupData(mPackage);
4861 } catch (RemoteException e) {
4862 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004863 } catch (Exception e) {
4864 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004865 } finally {
4866 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004867 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004868 mTransport.finishBackup();
4869 } catch (RemoteException e) {
4870 // can't happen; the transport is local
4871 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004872
4873 // Last but not least, release the cpu
4874 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004875 }
4876 }
4877 }
4878
Christopher Tate44a27902010-01-27 17:15:49 -08004879 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004880 HashSet<String> mQueue;
4881
Christopher Tate44a27902010-01-27 17:15:49 -08004882 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004883 mQueue = transportNames;
4884 }
4885
Christopher Tate4cc86e12009-09-21 19:36:51 -07004886 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004887 try {
4888 for (String transportName : mQueue) {
4889 IBackupTransport transport = getTransport(transportName);
4890 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004891 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004892 continue;
4893 }
4894
Joe Onorato8a9b2202010-02-26 18:56:32 -08004895 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004896 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004897 long startRealtime = SystemClock.elapsedRealtime();
4898 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004899
Christopher Tate4cc86e12009-09-21 19:36:51 -07004900 if (status == BackupConstants.TRANSPORT_OK) {
4901 status = transport.finishBackup();
4902 }
4903
4904 // Okay, the wipe really happened. Clean up our local bookkeeping.
4905 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004906 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004907 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004908 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004909 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004910 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004911 synchronized (mQueueLock) {
4912 recordInitPendingLocked(false, transportName);
4913 }
Dan Egnor726247c2009-09-29 19:12:31 -07004914 } else {
4915 // If this didn't work, requeue this one and try again
4916 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004917 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004918 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004919 synchronized (mQueueLock) {
4920 recordInitPendingLocked(true, transportName);
4921 }
4922 // do this via another alarm to make sure of the wakelock states
4923 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004924 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004925 + transportName + " resched in " + delay);
4926 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4927 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004928 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004929 }
4930 } catch (RemoteException e) {
4931 // can't happen; the transports are local
4932 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004933 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004934 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004935 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004936 mWakelock.release();
4937 }
4938 }
4939 }
4940
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004941 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004942 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004943 dataChangedImpl(packageName, targets);
4944 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004945
Christopher Tatea3d55342012-03-27 13:16:18 -07004946 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004947 // Record that we need a backup pass for the caller. Since multiple callers
4948 // may share a uid, we need to note all candidates within that uid and schedule
4949 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004950 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004951
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004952 if (targets == null) {
4953 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4954 + " uid=" + Binder.getCallingUid());
4955 return;
4956 }
4957
4958 synchronized (mQueueLock) {
4959 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004960 if (targets.contains(packageName)) {
4961 // Add the caller to the set of pending backups. If there is
4962 // one already there, then overwrite it, but no harm done.
4963 BackupRequest req = new BackupRequest(packageName);
4964 if (mPendingBackups.put(packageName, req) == null) {
4965 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004966
Christopher Tatea3d55342012-03-27 13:16:18 -07004967 // Journal this request in case of crash. The put()
4968 // operation returned null when this package was not already
4969 // in the set; we want to avoid touching the disk redundantly.
4970 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004971
Christopher Tatea3d55342012-03-27 13:16:18 -07004972 if (MORE_DEBUG) {
4973 int numKeys = mPendingBackups.size();
4974 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4975 for (BackupRequest b : mPendingBackups.values()) {
4976 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004977 }
4978 }
4979 }
4980 }
4981 }
4982 }
4983
4984 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004985 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004986 // If the caller does not hold the BACKUP permission, it can only request a
4987 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004988 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004989 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004990 synchronized (mBackupParticipants) {
4991 return mBackupParticipants.get(Binder.getCallingUid());
4992 }
4993 }
4994
4995 // a caller with full permission can ask to back up any participating app
4996 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004997 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004998 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004999 int N = mBackupParticipants.size();
5000 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005001 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07005002 if (s != null) {
5003 targets.addAll(s);
5004 }
5005 }
5006 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005007 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07005008 }
Christopher Tate46758122009-05-06 11:22:00 -07005009
Christopher Tatecde87f42009-06-12 12:55:53 -07005010 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005011 RandomAccessFile out = null;
5012 try {
5013 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5014 out = new RandomAccessFile(mJournal, "rws");
5015 out.seek(out.length());
5016 out.writeUTF(str);
5017 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005018 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005019 mJournal = null;
5020 } finally {
5021 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07005022 }
5023 }
5024
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005025 // ----- IBackupManager binder interface -----
5026
5027 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005028 final int callingUserHandle = UserHandle.getCallingUserId();
5029 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005030 // App is running under a non-owner user profile. For now, we do not back
5031 // up data from secondary user profiles.
5032 // TODO: backups for all user profiles.
5033 if (MORE_DEBUG) {
5034 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5035 + callingUserHandle);
5036 }
5037 return;
5038 }
5039
Christopher Tatea3d55342012-03-27 13:16:18 -07005040 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005041 if (targets == null) {
5042 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5043 + " uid=" + Binder.getCallingUid());
5044 return;
5045 }
5046
5047 mBackupHandler.post(new Runnable() {
5048 public void run() {
5049 dataChangedImpl(packageName, targets);
5050 }
5051 });
5052 }
5053
Christopher Tateee0e78a2009-07-02 11:17:03 -07005054 // Clear the given package's backup data from the current transport
5055 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005056 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005057 PackageInfo info;
5058 try {
5059 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5060 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005061 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07005062 return;
5063 }
5064
5065 // If the caller does not hold the BACKUP permission, it can only request a
5066 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07005067 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005068 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07005069 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5070 apps = mBackupParticipants.get(Binder.getCallingUid());
5071 } else {
5072 // a caller with full permission can ask to back up any participating app
5073 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08005074 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07005075 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07005076 int N = mBackupParticipants.size();
5077 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005078 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005079 if (s != null) {
5080 apps.addAll(s);
5081 }
5082 }
5083 }
5084
Christopher Tatea3d55342012-03-27 13:16:18 -07005085 // Is the given app an available participant?
5086 if (apps.contains(packageName)) {
5087 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5088 // found it; fire off the clear request
5089 synchronized (mQueueLock) {
5090 long oldId = Binder.clearCallingIdentity();
5091 mWakelock.acquire();
5092 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5093 new ClearParams(getTransport(mCurrentTransport), info));
5094 mBackupHandler.sendMessage(msg);
5095 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005096 }
5097 }
5098 }
5099
Christopher Tateace7f092009-06-15 18:07:25 -07005100 // Run a backup pass immediately for any applications that have declared
5101 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07005102 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04005103 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07005104
Joe Onorato8a9b2202010-02-26 18:56:32 -08005105 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07005106 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005107 // Because the alarms we are using can jitter, and we want an *immediate*
5108 // backup pass to happen, we restart the timer beginning with "next time,"
5109 // then manually fire the backup trigger intent ourselves.
5110 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07005111 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07005112 mRunBackupIntent.send();
5113 } catch (PendingIntent.CanceledException e) {
5114 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08005115 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07005116 }
Christopher Tate46758122009-05-06 11:22:00 -07005117 }
5118 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005119
Christopher Tated2c0cd42011-09-15 15:51:29 -07005120 boolean deviceIsProvisioned() {
5121 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07005122 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005123 }
5124
Christopher Tate4a627c72011-04-01 14:43:32 -07005125 // Run a *full* backup pass for the given package, writing the resulting data stream
5126 // to the supplied file descriptor. This method is synchronous and does not return
5127 // to the caller until the backup has been completed.
Christopher Tate294b5122013-02-19 14:08:59 -08005128 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5129 boolean includeObbs, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005130 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005131 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5132
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005133 final int callingUserHandle = UserHandle.getCallingUserId();
5134 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005135 throw new IllegalStateException("Backup supported only for the device owner");
5136 }
5137
Christopher Tate4a627c72011-04-01 14:43:32 -07005138 // Validate
5139 if (!doAllApps) {
5140 if (!includeShared) {
5141 // If we're backing up shared data (sdcard or equivalent), then we can run
5142 // without any supplied app names. Otherwise, we'd be doing no work, so
5143 // report the error.
5144 if (pkgList == null || pkgList.length == 0) {
5145 throw new IllegalArgumentException(
5146 "Backup requested but neither shared nor any apps named");
5147 }
5148 }
5149 }
5150
Christopher Tate4a627c72011-04-01 14:43:32 -07005151 long oldId = Binder.clearCallingIdentity();
5152 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005153 // Doesn't make sense to do a full backup prior to setup
5154 if (!deviceIsProvisioned()) {
5155 Slog.i(TAG, "Full backup not supported before setup");
5156 return;
5157 }
5158
5159 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
Christopher Tate294b5122013-02-19 14:08:59 -08005160 + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
Christopher Tated2c0cd42011-09-15 15:51:29 -07005161 + " pkgs=" + pkgList);
5162 Slog.i(TAG, "Beginning full backup...");
5163
Christopher Tate294b5122013-02-19 14:08:59 -08005164 FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5165 includeShared, doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005166 final int token = generateToken();
5167 synchronized (mFullConfirmations) {
5168 mFullConfirmations.put(token, params);
5169 }
5170
Christopher Tate75a99702011-05-18 16:28:19 -07005171 // start up the confirmation UI
5172 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5173 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5174 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005175 mFullConfirmations.delete(token);
5176 return;
5177 }
Christopher Tate75a99702011-05-18 16:28:19 -07005178
5179 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005180 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5181
5182 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005183 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005184
5185 // wait for the backup to be performed
5186 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5187 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005188 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005189 try {
5190 fd.close();
5191 } catch (IOException e) {
5192 // just eat it
5193 }
Christopher Tate75a99702011-05-18 16:28:19 -07005194 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005195 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005196 }
Christopher Tate75a99702011-05-18 16:28:19 -07005197 }
5198
5199 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005200 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005201
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005202 final int callingUserHandle = UserHandle.getCallingUserId();
5203 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005204 throw new IllegalStateException("Restore supported only for the device owner");
5205 }
5206
Christopher Tate75a99702011-05-18 16:28:19 -07005207 long oldId = Binder.clearCallingIdentity();
5208
5209 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005210 // Check whether the device has been provisioned -- we don't handle
5211 // full restores prior to completing the setup process.
5212 if (!deviceIsProvisioned()) {
5213 Slog.i(TAG, "Full restore not permitted before setup");
5214 return;
5215 }
5216
5217 Slog.i(TAG, "Beginning full restore...");
5218
Christopher Tate75a99702011-05-18 16:28:19 -07005219 FullRestoreParams params = new FullRestoreParams(fd);
5220 final int token = generateToken();
5221 synchronized (mFullConfirmations) {
5222 mFullConfirmations.put(token, params);
5223 }
5224
5225 // start up the confirmation UI
5226 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5227 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5228 Slog.e(TAG, "Unable to launch full restore confirmation");
5229 mFullConfirmations.delete(token);
5230 return;
5231 }
5232
5233 // make sure the screen is lit for the user interaction
5234 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5235
5236 // start the confirmation countdown
5237 startConfirmationTimeout(token, params);
5238
5239 // wait for the restore to be performed
5240 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5241 waitForCompletion(params);
5242 } finally {
5243 try {
5244 fd.close();
5245 } catch (IOException e) {
5246 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5247 }
5248 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005249 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005250 }
5251 }
5252
5253 boolean startConfirmationUi(int token, String action) {
5254 try {
5255 Intent confIntent = new Intent(action);
5256 confIntent.setClassName("com.android.backupconfirm",
5257 "com.android.backupconfirm.BackupRestoreConfirmation");
5258 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5259 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5260 mContext.startActivity(confIntent);
5261 } catch (ActivityNotFoundException e) {
5262 return false;
5263 }
5264 return true;
5265 }
5266
5267 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005268 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005269 + TIMEOUT_FULL_CONFIRMATION + " millis");
5270 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5271 token, 0, params);
5272 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005273 }
5274
5275 void waitForCompletion(FullParams params) {
5276 synchronized (params.latch) {
5277 while (params.latch.get() == false) {
5278 try {
5279 params.latch.wait();
5280 } catch (InterruptedException e) { /* never interrupted */ }
5281 }
5282 }
5283 }
5284
5285 void signalFullBackupRestoreCompletion(FullParams params) {
5286 synchronized (params.latch) {
5287 params.latch.set(true);
5288 params.latch.notifyAll();
5289 }
5290 }
5291
5292 // Confirm that the previously-requested full backup/restore operation can proceed. This
5293 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005294 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005295 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005296 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005297 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5298 + " allow=" + allow);
5299
5300 // TODO: possibly require not just this signature-only permission, but even
5301 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005302 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005303
5304 long oldId = Binder.clearCallingIdentity();
5305 try {
5306
5307 FullParams params;
5308 synchronized (mFullConfirmations) {
5309 params = mFullConfirmations.get(token);
5310 if (params != null) {
5311 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5312 mFullConfirmations.delete(token);
5313
5314 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005315 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005316 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005317 : MSG_RUN_FULL_RESTORE;
5318
Christopher Tate728a1c42011-07-28 18:03:03 -07005319 params.observer = observer;
5320 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005321
5322 boolean isEncrypted;
5323 try {
5324 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5325 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5326 } catch (RemoteException e) {
5327 // couldn't contact the mount service; fail "safe" and assume encryption
5328 Slog.e(TAG, "Unable to contact mount service!");
5329 isEncrypted = true;
5330 }
5331 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005332
Christopher Tate75a99702011-05-18 16:28:19 -07005333 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005334 mWakelock.acquire();
5335 Message msg = mBackupHandler.obtainMessage(verb, params);
5336 mBackupHandler.sendMessage(msg);
5337 } else {
5338 Slog.w(TAG, "User rejected full backup/restore operation");
5339 // indicate completion without having actually transferred any data
5340 signalFullBackupRestoreCompletion(params);
5341 }
5342 } else {
5343 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5344 }
5345 }
5346 } finally {
5347 Binder.restoreCallingIdentity(oldId);
5348 }
5349 }
5350
Christopher Tate8031a3d2009-07-06 16:36:05 -07005351 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005352 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005354 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005355
Joe Onorato8a9b2202010-02-26 18:56:32 -08005356 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005357
Christopher Tate6ef58a12009-06-29 14:56:28 -07005358 boolean wasEnabled = mEnabled;
5359 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005360 Settings.Secure.putInt(mContext.getContentResolver(),
5361 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005362 mEnabled = enable;
5363 }
5364
Christopher Tate49401dd2009-07-01 12:34:29 -07005365 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005366 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005367 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005368 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005369 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005370 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005371 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005372
Christopher Tateb6787f22009-07-02 17:40:45 -07005373 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005374
5375 // This also constitutes an opt-out, so we wipe any data for
5376 // this device from the backend. We start that process with
5377 // an alarm in order to guarantee wakelock states.
5378 if (wasEnabled && mProvisioned) {
5379 // NOTE: we currently flush every registered transport, not just
5380 // the currently-active one.
5381 HashSet<String> allTransports;
5382 synchronized (mTransports) {
5383 allTransports = new HashSet<String>(mTransports.keySet());
5384 }
5385 // build the set of transports for which we are posting an init
5386 for (String transport : allTransports) {
5387 recordInitPendingLocked(true, transport);
5388 }
5389 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5390 mRunInitIntent);
5391 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005392 }
5393 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005394 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005395
Christopher Tatecce9da52010-02-03 15:11:15 -08005396 // Enable/disable automatic restore of app data at install time
5397 public void setAutoRestore(boolean doAutoRestore) {
5398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005399 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005400
Joe Onorato8a9b2202010-02-26 18:56:32 -08005401 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005402
5403 synchronized (this) {
5404 Settings.Secure.putInt(mContext.getContentResolver(),
5405 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5406 mAutoRestore = doAutoRestore;
5407 }
5408 }
5409
Christopher Tate8031a3d2009-07-06 16:36:05 -07005410 // Mark the backup service as having been provisioned
5411 public void setBackupProvisioned(boolean available) {
5412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5413 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005414 /*
5415 * This is now a no-op; provisioning is simply the device's own setup state.
5416 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005417 }
5418
5419 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005420 // We used to use setInexactRepeating(), but that may be linked to
5421 // backups running at :00 more often than not, creating load spikes.
5422 // Schedule at an exact time for now, and also add a bit of "fuzz".
5423
5424 Random random = new Random();
5425 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5426 random.nextInt(FUZZ_MILLIS);
5427 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5428 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005429 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005430 }
5431
Christopher Tate6ef58a12009-06-29 14:56:28 -07005432 // Report whether the backup mechanism is currently enabled
5433 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005434 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005435 return mEnabled; // no need to synchronize just to read it
5436 }
5437
Christopher Tate91717492009-06-26 21:07:13 -07005438 // Report the name of the currently active transport
5439 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005440 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005441 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005442 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005443 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005444 }
5445
Christopher Tate91717492009-06-26 21:07:13 -07005446 // Report all known, available backup transports
5447 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005448 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005449
Christopher Tate91717492009-06-26 21:07:13 -07005450 String[] list = null;
5451 ArrayList<String> known = new ArrayList<String>();
5452 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5453 if (entry.getValue() != null) {
5454 known.add(entry.getKey());
5455 }
5456 }
5457
5458 if (known.size() > 0) {
5459 list = new String[known.size()];
5460 known.toArray(list);
5461 }
5462 return list;
5463 }
5464
5465 // Select which transport to use for the next backup operation. If the given
5466 // name is not one of the available transports, no action is taken and the method
5467 // returns null.
5468 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005469 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005470
5471 synchronized (mTransports) {
5472 String prevTransport = null;
5473 if (mTransports.get(transport) != null) {
5474 prevTransport = mCurrentTransport;
5475 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005476 Settings.Secure.putString(mContext.getContentResolver(),
5477 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005478 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005479 + " returning " + prevTransport);
5480 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005481 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005482 }
5483 return prevTransport;
5484 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005485 }
5486
Christopher Tatef5e1c292010-12-08 18:40:26 -08005487 // Supply the configuration Intent for the given transport. If the name is not one
5488 // of the available transports, or if the transport does not supply any configuration
5489 // UI, the method returns null.
5490 public Intent getConfigurationIntent(String transportName) {
5491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5492 "getConfigurationIntent");
5493
5494 synchronized (mTransports) {
5495 final IBackupTransport transport = mTransports.get(transportName);
5496 if (transport != null) {
5497 try {
5498 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005499 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005500 + intent);
5501 return intent;
5502 } catch (RemoteException e) {
5503 /* fall through to return null */
5504 }
5505 }
5506 }
5507
5508 return null;
5509 }
5510
5511 // Supply the configuration summary string for the given transport. If the name is
5512 // not one of the available transports, or if the transport does not supply any
5513 // summary / destination string, the method can return null.
5514 //
5515 // This string is used VERBATIM as the summary text of the relevant Settings item!
5516 public String getDestinationString(String transportName) {
5517 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005518 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005519
5520 synchronized (mTransports) {
5521 final IBackupTransport transport = mTransports.get(transportName);
5522 if (transport != null) {
5523 try {
5524 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005525 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005526 return text;
5527 } catch (RemoteException e) {
5528 /* fall through to return null */
5529 }
5530 }
5531 }
5532
5533 return null;
5534 }
5535
Christopher Tate043dadc2009-06-02 16:11:00 -07005536 // Callback: a requested backup agent has been instantiated. This should only
5537 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005538 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005539 synchronized(mAgentConnectLock) {
5540 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005541 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005542 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5543 mConnectedAgent = agent;
5544 mConnecting = false;
5545 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005546 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005547 + " claiming agent connected");
5548 }
5549 mAgentConnectLock.notifyAll();
5550 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005551 }
5552
5553 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5554 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005555 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005556 public void agentDisconnected(String packageName) {
5557 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005558 synchronized(mAgentConnectLock) {
5559 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5560 mConnectedAgent = null;
5561 mConnecting = false;
5562 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005563 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005564 + " claiming agent disconnected");
5565 }
5566 mAgentConnectLock.notifyAll();
5567 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005568 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005569
Christopher Tate1bb69062010-02-19 17:02:12 -08005570 // An application being installed will need a restore pass, then the Package Manager
5571 // will need to be told when the restore is finished.
5572 public void restoreAtInstall(String packageName, int token) {
5573 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005574 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005575 + " attemping install-time restore");
5576 return;
5577 }
5578
5579 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005580 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005581 + " token=" + Integer.toHexString(token)
5582 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005583
Christopher Tatef0872722010-02-25 15:22:48 -08005584 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005585 // okay, we're going to attempt a restore of this package from this restore set.
5586 // The eventual message back into the Package Manager to run the post-install
5587 // steps for 'token' will be issued from the restore handling code.
5588
5589 // We can use a synthetic PackageInfo here because:
5590 // 1. We know it's valid, since the Package Manager supplied the name
5591 // 2. Only the packageName field will be used by the restore code
5592 PackageInfo pkg = new PackageInfo();
5593 pkg.packageName = packageName;
5594
5595 mWakelock.acquire();
5596 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5597 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005598 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005599 mBackupHandler.sendMessage(msg);
5600 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005601 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5602 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005603 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005604 try {
5605 mPackageManagerBinder.finishPackageInstall(token);
5606 } catch (RemoteException e) { /* can't happen */ }
5607 }
5608 }
5609
Christopher Tate8c850b72009-06-07 19:33:20 -07005610 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005611 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5612 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5613 + " transport=" + transport);
5614
5615 boolean needPermission = true;
5616 if (transport == null) {
5617 transport = mCurrentTransport;
5618
5619 if (packageName != null) {
5620 PackageInfo app = null;
5621 try {
5622 app = mPackageManager.getPackageInfo(packageName, 0);
5623 } catch (NameNotFoundException nnf) {
5624 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5625 throw new IllegalArgumentException("Package " + packageName + " not found");
5626 }
5627
5628 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5629 // So: using the current active transport, and the caller has asked
5630 // that its own package will be restored. In this narrow use case
5631 // we do not require the caller to hold the permission.
5632 needPermission = false;
5633 }
5634 }
5635 }
5636
5637 if (needPermission) {
5638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5639 "beginRestoreSession");
5640 } else {
5641 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5642 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005643
5644 synchronized(this) {
5645 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005646 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005647 return null;
5648 }
Chris Tate44ab8452010-11-16 15:10:49 -08005649 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005650 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005651 }
5652 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005653 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005654
Christopher Tate73a3cb32010-12-13 18:27:26 -08005655 void clearRestoreSession(ActiveRestoreSession currentSession) {
5656 synchronized(this) {
5657 if (currentSession != mActiveRestoreSession) {
5658 Slog.e(TAG, "ending non-current restore session");
5659 } else {
5660 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5661 mActiveRestoreSession = null;
5662 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5663 }
5664 }
5665 }
5666
Christopher Tate44a27902010-01-27 17:15:49 -08005667 // Note that a currently-active backup agent has notified us that it has
5668 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005669 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005670 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005671 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5672 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005673 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005674 op = mCurrentOperations.get(token);
5675 if (op != null) {
5676 op.state = OP_ACKNOWLEDGED;
5677 }
Christopher Tate44a27902010-01-27 17:15:49 -08005678 mCurrentOpLock.notifyAll();
5679 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005680
5681 // The completion callback, if any, is invoked on the handler
5682 if (op != null && op.callback != null) {
5683 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5684 mBackupHandler.sendMessage(msg);
5685 }
Christopher Tate44a27902010-01-27 17:15:49 -08005686 }
5687
Christopher Tate9b3905c2009-06-08 15:24:01 -07005688 // ----- Restore session -----
5689
Christopher Tate80202c82010-01-25 19:37:47 -08005690 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005691 private static final String TAG = "RestoreSession";
5692
Chris Tate44ab8452010-11-16 15:10:49 -08005693 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005694 private IBackupTransport mRestoreTransport = null;
5695 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005696 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005697
Chris Tate44ab8452010-11-16 15:10:49 -08005698 ActiveRestoreSession(String packageName, String transport) {
5699 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005700 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005701 }
5702
5703 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005704 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005706 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005707 if (observer == null) {
5708 throw new IllegalArgumentException("Observer must not be null");
5709 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005710
Christopher Tate73a3cb32010-12-13 18:27:26 -08005711 if (mEnded) {
5712 throw new IllegalStateException("Restore session already ended");
5713 }
5714
Christopher Tate1bb69062010-02-19 17:02:12 -08005715 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005716 try {
Christopher Tate43383042009-07-13 15:17:13 -07005717 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005718 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005719 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005720 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005721 // spin off the transport request to our service thread
5722 mWakelock.acquire();
5723 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5724 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5725 mBackupHandler.sendMessage(msg);
5726 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005727 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005728 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005729 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005730 } finally {
5731 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005732 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005733 }
5734
Christopher Tate84725812010-02-04 15:52:40 -08005735 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005736 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5737 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005738
Chris Tate44ab8452010-11-16 15:10:49 -08005739 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005740 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005741
Christopher Tate73a3cb32010-12-13 18:27:26 -08005742 if (mEnded) {
5743 throw new IllegalStateException("Restore session already ended");
5744 }
5745
Dan Egnor0084da52009-07-29 12:57:16 -07005746 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005747 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5748 return -1;
5749 }
5750
5751 if (mPackageName != null) {
5752 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005753 return -1;
5754 }
5755
Christopher Tate21ab6a52009-09-24 18:01:46 -07005756 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005757 for (int i = 0; i < mRestoreSets.length; i++) {
5758 if (token == mRestoreSets[i].token) {
5759 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005760 mWakelock.acquire();
5761 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005762 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005763 mBackupHandler.sendMessage(msg);
5764 Binder.restoreCallingIdentity(oldId);
5765 return 0;
5766 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005767 }
5768 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005769
Joe Onorato8a9b2202010-02-26 18:56:32 -08005770 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005771 return -1;
5772 }
5773
Christopher Tate284f1bb2011-07-07 14:31:18 -07005774 public synchronized int restoreSome(long token, IRestoreObserver observer,
5775 String[] packages) {
5776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5777 "performRestore");
5778
5779 if (DEBUG) {
5780 StringBuilder b = new StringBuilder(128);
5781 b.append("restoreSome token=");
5782 b.append(Long.toHexString(token));
5783 b.append(" observer=");
5784 b.append(observer.toString());
5785 b.append(" packages=");
5786 if (packages == null) {
5787 b.append("null");
5788 } else {
5789 b.append('{');
5790 boolean first = true;
5791 for (String s : packages) {
5792 if (!first) {
5793 b.append(", ");
5794 } else first = false;
5795 b.append(s);
5796 }
5797 b.append('}');
5798 }
5799 Slog.d(TAG, b.toString());
5800 }
5801
5802 if (mEnded) {
5803 throw new IllegalStateException("Restore session already ended");
5804 }
5805
5806 if (mRestoreTransport == null || mRestoreSets == null) {
5807 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5808 return -1;
5809 }
5810
5811 if (mPackageName != null) {
5812 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5813 return -1;
5814 }
5815
5816 synchronized (mQueueLock) {
5817 for (int i = 0; i < mRestoreSets.length; i++) {
5818 if (token == mRestoreSets[i].token) {
5819 long oldId = Binder.clearCallingIdentity();
5820 mWakelock.acquire();
5821 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5822 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5823 packages, true);
5824 mBackupHandler.sendMessage(msg);
5825 Binder.restoreCallingIdentity(oldId);
5826 return 0;
5827 }
5828 }
5829 }
5830
5831 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5832 return -1;
5833 }
5834
Christopher Tate84725812010-02-04 15:52:40 -08005835 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005836 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005837
Christopher Tate73a3cb32010-12-13 18:27:26 -08005838 if (mEnded) {
5839 throw new IllegalStateException("Restore session already ended");
5840 }
5841
Chris Tate44ab8452010-11-16 15:10:49 -08005842 if (mPackageName != null) {
5843 if (! mPackageName.equals(packageName)) {
5844 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5845 + " on session for package " + mPackageName);
5846 return -1;
5847 }
5848 }
5849
Christopher Tate84725812010-02-04 15:52:40 -08005850 PackageInfo app = null;
5851 try {
5852 app = mPackageManager.getPackageInfo(packageName, 0);
5853 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005854 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005855 return -1;
5856 }
5857
5858 // If the caller is not privileged and is not coming from the target
5859 // app's uid, throw a permission exception back to the caller.
5860 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5861 Binder.getCallingPid(), Binder.getCallingUid());
5862 if ((perm == PackageManager.PERMISSION_DENIED) &&
5863 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005864 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005865 + " or calling uid=" + Binder.getCallingUid());
5866 throw new SecurityException("No permission to restore other packages");
5867 }
5868
Christopher Tate7d411a32010-02-26 11:27:08 -08005869 // If the package has no backup agent, we obviously cannot proceed
5870 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005871 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005872 return -1;
5873 }
5874
Christopher Tate84725812010-02-04 15:52:40 -08005875 // So far so good; we're allowed to try to restore this package. Now
5876 // check whether there is data for it in the current dataset, falling back
5877 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005878 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005879
5880 // If we didn't come up with a place to look -- no ancestral dataset and
5881 // the app has never been backed up from this device -- there's nothing
5882 // to do but return failure.
5883 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005884 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005885 return -1;
5886 }
5887
5888 // Ready to go: enqueue the restore request and claim success
5889 long oldId = Binder.clearCallingIdentity();
5890 mWakelock.acquire();
5891 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005892 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005893 mBackupHandler.sendMessage(msg);
5894 Binder.restoreCallingIdentity(oldId);
5895 return 0;
5896 }
5897
Christopher Tate73a3cb32010-12-13 18:27:26 -08005898 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5899 class EndRestoreRunnable implements Runnable {
5900 BackupManagerService mBackupManager;
5901 ActiveRestoreSession mSession;
5902
5903 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5904 mBackupManager = manager;
5905 mSession = session;
5906 }
5907
5908 public void run() {
5909 // clean up the session's bookkeeping
5910 synchronized (mSession) {
5911 try {
5912 if (mSession.mRestoreTransport != null) {
5913 mSession.mRestoreTransport.finishRestore();
5914 }
5915 } catch (Exception e) {
5916 Slog.e(TAG, "Error in finishRestore", e);
5917 } finally {
5918 mSession.mRestoreTransport = null;
5919 mSession.mEnded = true;
5920 }
5921 }
5922
5923 // clean up the BackupManagerService side of the bookkeeping
5924 // and cancel any pending timeout message
5925 mBackupManager.clearRestoreSession(mSession);
5926 }
5927 }
5928
Dan Egnor0084da52009-07-29 12:57:16 -07005929 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005930 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005931
Christopher Tate73a3cb32010-12-13 18:27:26 -08005932 if (mEnded) {
5933 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005934 }
5935
Christopher Tate73a3cb32010-12-13 18:27:26 -08005936 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005937 }
5938 }
5939
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005940 @Override
5941 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005942 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5943
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005944 long identityToken = Binder.clearCallingIdentity();
5945 try {
5946 dumpInternal(pw);
5947 } finally {
5948 Binder.restoreCallingIdentity(identityToken);
5949 }
5950 }
5951
5952 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005953 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005954 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005955 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005956 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005957 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005958 if (mBackupRunning) pw.println("Backup currently running");
5959 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005960 + " (now = " + System.currentTimeMillis() + ')');
5961 pw.println(" next scheduled: " + mNextBackupPass);
5962
Christopher Tate91717492009-06-26 21:07:13 -07005963 pw.println("Available transports:");
5964 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005965 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5966 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005967 IBackupTransport transport = getTransport(t);
5968 File dir = new File(mBaseStateDir, transport.transportDirName());
5969 pw.println(" destination: " + transport.currentDestinationString());
5970 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005971 for (File f : dir.listFiles()) {
5972 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5973 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005974 } catch (Exception e) {
5975 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005976 pw.println(" Error: " + e);
5977 }
Christopher Tate91717492009-06-26 21:07:13 -07005978 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005979
5980 pw.println("Pending init: " + mPendingInits.size());
5981 for (String s : mPendingInits) {
5982 pw.println(" " + s);
5983 }
5984
Christopher Tate6de74ff2012-01-17 15:20:32 -08005985 if (DEBUG_BACKUP_TRACE) {
5986 synchronized (mBackupTrace) {
5987 if (!mBackupTrace.isEmpty()) {
5988 pw.println("Most recent backup trace:");
5989 for (String s : mBackupTrace) {
5990 pw.println(" " + s);
5991 }
5992 }
5993 }
5994 }
5995
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005996 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005997 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005998 for (int i=0; i<N; i++) {
5999 int uid = mBackupParticipants.keyAt(i);
6000 pw.print(" uid: ");
6001 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07006002 HashSet<String> participants = mBackupParticipants.valueAt(i);
6003 for (String app: participants) {
6004 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006005 }
6006 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006007
Christopher Tateb49ceb32010-02-08 16:22:24 -08006008 pw.println("Ancestral packages: "
6009 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07006010 if (mAncestralPackages != null) {
6011 for (String pkg : mAncestralPackages) {
6012 pw.println(" " + pkg);
6013 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08006014 }
6015
Christopher Tate73e02522009-07-15 14:18:26 -07006016 pw.println("Ever backed up: " + mEverStoredApps.size());
6017 for (String pkg : mEverStoredApps) {
6018 pw.println(" " + pkg);
6019 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006020
6021 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07006022 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07006023 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07006024 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006025 }
6026 }
Christopher Tate487529a2009-04-29 14:03:25 -07006027}