blob: f3ebdb21ff93e77fceabc4d9439f18ecf18bb122 [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 Tatedfa47b56e2009-12-22 16:01:32 -08001308 // Nothing further to do in the unregistration case
1309 return;
1310 }
Christopher Tate91717492009-06-26 21:07:13 -07001311 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001312
1313 // If the init sentinel file exists, we need to be sure to perform the init
1314 // as soon as practical. We also create the state directory at registration
1315 // time to ensure it's present from the outset.
1316 try {
1317 String transportName = transport.transportDirName();
1318 File stateDir = new File(mBaseStateDir, transportName);
1319 stateDir.mkdirs();
1320
1321 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1322 if (initSentinel.exists()) {
1323 synchronized (mQueueLock) {
1324 mPendingInits.add(transportName);
1325
1326 // TODO: pick a better starting time than now + 1 minute
1327 long delay = 1000 * 60; // one minute, in milliseconds
1328 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1329 System.currentTimeMillis() + delay, mRunInitIntent);
1330 }
1331 }
1332 } catch (RemoteException e) {
1333 // can't happen, the transport is local
1334 }
Christopher Tate91717492009-06-26 21:07:13 -07001335 }
1336
Christopher Tate3799bc22009-05-06 16:13:56 -07001337 // ----- Track installation/removal of packages -----
1338 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1339 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001340 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001341
Christopher Tate3799bc22009-05-06 16:13:56 -07001342 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001343 boolean replacing = false;
1344 boolean added = false;
1345 Bundle extras = intent.getExtras();
1346 String pkgList[] = null;
1347 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001348 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001349 Uri uri = intent.getData();
1350 if (uri == null) {
1351 return;
1352 }
1353 String pkgName = uri.getSchemeSpecificPart();
1354 if (pkgName != null) {
1355 pkgList = new String[] { pkgName };
1356 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001357 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1358 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001359 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001360 added = true;
1361 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001362 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001363 added = false;
1364 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1365 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001366
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001367 if (pkgList == null || pkgList.length == 0) {
1368 return;
1369 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001370
1371 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001372 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001373 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001374 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001375 // This is the package-replaced case; we just remove the entry
1376 // under the old uid and fall through to re-add.
1377 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001378 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001379 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001380 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001381 } else {
1382 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1384 } else {
1385 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001386 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001387 }
1388 }
1389 }
1390 }
1391 };
1392
Dan Egnor87a02bc2009-06-17 02:30:10 -07001393 // ----- Track connection to GoogleBackupTransport service -----
1394 ServiceConnection mGoogleConnection = new ServiceConnection() {
1395 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001397 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001398 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001399 }
1400
1401 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001402 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001403 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001404 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001405 }
1406 };
1407
Christopher Tate0bacfd22012-01-11 14:41:19 -08001408 // Add the backup agents in the given packages to our set of known backup participants.
1409 // If 'packageNames' is null, adds all backup agents in the whole system.
1410 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001411 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001412 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001413 if (packageNames != null) {
1414 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1415 for (String packageName : packageNames) {
1416 addPackageParticipantsLockedInner(packageName, targetApps);
1417 }
1418 } else {
1419 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1420 addPackageParticipantsLockedInner(null, targetApps);
1421 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001422 }
1423
Christopher Tate181fafa2009-05-14 11:12:14 -07001424 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001425 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001426 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001427 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001428 }
1429
Dan Egnorefe52642009-06-24 00:16:33 -07001430 for (PackageInfo pkg : targetPkgs) {
1431 if (packageName == null || pkg.packageName.equals(packageName)) {
1432 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001433 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001434 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001435 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001436 mBackupParticipants.put(uid, set);
1437 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001438 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001439 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001440
Christopher Tatee82f68d2012-10-23 15:07:38 -07001441 // Schedule a backup for it on general principles
1442 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1443 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001444 }
Christopher Tate487529a2009-04-29 14:03:25 -07001445 }
1446 }
1447
Christopher Tate0bacfd22012-01-11 14:41:19 -08001448 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001449 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001450 if (packageNames == null) {
1451 Slog.w(TAG, "removePackageParticipants with null list");
1452 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001453 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001454
Christopher Tatea3d55342012-03-27 13:16:18 -07001455 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1456 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001457 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001458 // Known previous UID, so we know which package set to check
1459 HashSet<String> set = mBackupParticipants.get(oldUid);
1460 if (set != null && set.contains(pkg)) {
1461 removePackageFromSetLocked(set, pkg);
1462 if (set.isEmpty()) {
1463 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1464 mBackupParticipants.remove(oldUid);
1465 }
1466 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001467 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001468 }
1469
Christopher Tatea3d55342012-03-27 13:16:18 -07001470 private void removePackageFromSetLocked(final HashSet<String> set,
1471 final String packageName) {
1472 if (set.contains(packageName)) {
1473 // Found it. Remove this one package from the bookkeeping, and
1474 // if it's the last participating app under this uid we drop the
1475 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001476 // Note that we deliberately leave it 'known' in the "ever backed up"
1477 // bookkeeping so that its current-dataset data will be retrieved
1478 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001479 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001480 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001481 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001482 }
1483 }
1484
Christopher Tate181fafa2009-05-14 11:12:14 -07001485 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001486 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001487 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001488 int flags = PackageManager.GET_SIGNATURES;
1489 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1490 int N = packages.size();
1491 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001492 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001493 try {
1494 ApplicationInfo app = pkg.applicationInfo;
1495 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001496 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001497 packages.remove(a);
1498 }
1499 else {
1500 // we will need the shared library path, so look that up and store it here
1501 app = mPackageManager.getApplicationInfo(pkg.packageName,
1502 PackageManager.GET_SHARED_LIBRARY_FILES);
1503 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1504 }
1505 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001506 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001507 }
1508 }
Dan Egnorefe52642009-06-24 00:16:33 -07001509 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001510 }
Christopher Tateaa088442009-06-16 18:25:46 -07001511
Christopher Tate84725812010-02-04 15:52:40 -08001512 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001513 // backed up at least once
1514 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001515 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1516
1517 synchronized (mEverStoredApps) {
1518 if (!mEverStoredApps.add(packageName)) return;
1519
1520 RandomAccessFile out = null;
1521 try {
1522 out = new RandomAccessFile(mEverStored, "rws");
1523 out.seek(out.length());
1524 out.writeUTF(packageName);
1525 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001526 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001527 } finally {
1528 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001529 }
1530 }
1531 }
1532
Christopher Tatee97e8072009-07-15 16:45:50 -07001533 // Remove our awareness of having ever backed up the given package
1534 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001535 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1536 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001537
Dan Egnor852f8e42009-09-30 11:20:45 -07001538 synchronized (mEverStoredApps) {
1539 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1540 // we'll recognize on initialization time that the package no longer
1541 // exists and fix it up then.
1542 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1543 RandomAccessFile known = null;
1544 try {
1545 known = new RandomAccessFile(tempKnownFile, "rws");
1546 mEverStoredApps.remove(packageName);
1547 for (String s : mEverStoredApps) {
1548 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001549 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001550 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001551 known.close();
1552 known = null;
1553 if (!tempKnownFile.renameTo(mEverStored)) {
1554 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1555 }
1556 } catch (IOException e) {
1557 // Bad: we couldn't create the new copy. For safety's sake we
1558 // abandon the whole process and remove all what's-backed-up
1559 // state entirely, meaning we'll force a backup pass for every
1560 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001561 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001562 mEverStoredApps.clear();
1563 tempKnownFile.delete();
1564 mEverStored.delete();
1565 } finally {
1566 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001567 }
1568 }
1569 }
1570
Christopher Tateb49ceb32010-02-08 16:22:24 -08001571 // Persistently record the current and ancestral backup tokens as well
1572 // as the set of packages with data [supposedly] available in the
1573 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001574 void writeRestoreTokens() {
1575 try {
1576 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001577
1578 // First, the version number of this record, for futureproofing
1579 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1580
1581 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001582 af.writeLong(mAncestralToken);
1583 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001584
1585 // Now write the set of ancestral packages
1586 if (mAncestralPackages == null) {
1587 af.writeInt(-1);
1588 } else {
1589 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001590 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001591 for (String pkgName : mAncestralPackages) {
1592 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001593 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001594 }
1595 }
Christopher Tate84725812010-02-04 15:52:40 -08001596 af.close();
1597 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001598 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001599 }
1600 }
1601
Dan Egnor87a02bc2009-06-17 02:30:10 -07001602 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001603 private IBackupTransport getTransport(String transportName) {
1604 synchronized (mTransports) {
1605 IBackupTransport transport = mTransports.get(transportName);
1606 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001607 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001608 }
1609 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001610 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001611 }
1612
Christopher Tatedf01dea2009-06-09 20:45:02 -07001613 // fire off a backup agent, blocking until it attaches or times out
1614 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1615 IBackupAgent agent = null;
1616 synchronized(mAgentConnectLock) {
1617 mConnecting = true;
1618 mConnectedAgent = null;
1619 try {
1620 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001622
1623 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001624 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1626 while (mConnecting && mConnectedAgent == null
1627 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001629 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001630 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001631 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001632 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001633 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 return null;
1635 }
1636 }
1637
1638 // if we timed out with no connect, abort and move on
1639 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001641 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001642 return null;
1643 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001644 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001645 agent = mConnectedAgent;
1646 }
1647 } catch (RemoteException e) {
1648 // can't happen
1649 }
1650 }
1651 return agent;
1652 }
1653
Christopher Tatec7b31e32009-06-10 15:49:30 -07001654 // clear an application's data, blocking until the operation completes or times out
1655 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001656 // Don't wipe packages marked allowClearUserData=false
1657 try {
1658 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1659 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001660 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001661 + packageName);
1662 return;
1663 }
1664 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001665 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001666 return;
1667 }
1668
Christopher Tatec7b31e32009-06-10 15:49:30 -07001669 ClearDataObserver observer = new ClearDataObserver();
1670
1671 synchronized(mClearDataLock) {
1672 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001673 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001674 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001675 } catch (RemoteException e) {
1676 // can't happen because the activity manager is in this process
1677 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001678
1679 // only wait 10 seconds for the clear data to happen
1680 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1681 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1682 try {
1683 mClearDataLock.wait(5000);
1684 } catch (InterruptedException e) {
1685 // won't happen, but still.
1686 mClearingData = false;
1687 }
1688 }
1689 }
1690 }
1691
1692 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001693 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001694 synchronized(mClearDataLock) {
1695 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001696 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001697 }
1698 }
1699 }
1700
Christopher Tate1bb69062010-02-19 17:02:12 -08001701 // Get the restore-set token for the best-available restore set for this package:
1702 // the active set if possible, else the ancestral one. Returns zero if none available.
1703 long getAvailableRestoreToken(String packageName) {
1704 long token = mAncestralToken;
1705 synchronized (mQueueLock) {
1706 if (mEverStoredApps.contains(packageName)) {
1707 token = mCurrentToken;
1708 }
1709 }
1710 return token;
1711 }
1712
Christopher Tate44a27902010-01-27 17:15:49 -08001713 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001714 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1715
1716 interface BackupRestoreTask {
1717 // Execute one tick of whatever state machine the task implements
1718 void execute();
1719
1720 // An operation that wanted a callback has completed
1721 void operationComplete();
1722
1723 // An operation that wanted a callback has timed out
1724 void handleTimeout();
1725 }
1726
1727 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1728 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1729 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001730 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001731 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1732
1733 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1734 mBackupHandler.sendMessageDelayed(msg, interval);
1735 }
1736 }
1737
1738 // synchronous waiter case
1739 boolean waitUntilOperationComplete(int token) {
1740 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1741 + Integer.toHexString(token));
1742 int finalState = OP_PENDING;
1743 Operation op = null;
1744 synchronized (mCurrentOpLock) {
1745 while (true) {
1746 op = mCurrentOperations.get(token);
1747 if (op == null) {
1748 // mysterious disappearance: treat as success with no callback
1749 break;
1750 } else {
1751 if (op.state == OP_PENDING) {
1752 try {
1753 mCurrentOpLock.wait();
1754 } catch (InterruptedException e) {}
1755 // When the wait is notified we loop around and recheck the current state
1756 } else {
1757 // No longer pending; we're done
1758 finalState = op.state;
1759 break;
1760 }
Christopher Tate44a27902010-01-27 17:15:49 -08001761 }
Christopher Tate44a27902010-01-27 17:15:49 -08001762 }
1763 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001764
Christopher Tate44a27902010-01-27 17:15:49 -08001765 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001766 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001767 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001768 return finalState == OP_ACKNOWLEDGED;
1769 }
1770
Christopher Tate8e294d42011-08-31 20:37:12 -07001771 void handleTimeout(int token, Object obj) {
1772 // Notify any synchronous waiters
1773 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001774 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001775 op = mCurrentOperations.get(token);
1776 if (MORE_DEBUG) {
1777 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1778 + " but no op found");
1779 }
1780 int state = (op != null) ? op.state : OP_TIMEOUT;
1781 if (state == OP_PENDING) {
1782 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1783 op.state = OP_TIMEOUT;
1784 mCurrentOperations.put(token, op);
1785 }
1786 mCurrentOpLock.notifyAll();
1787 }
1788
1789 // If there's a TimeoutHandler for this event, call it
1790 if (op != null && op.callback != null) {
1791 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001792 }
Christopher Tate44a27902010-01-27 17:15:49 -08001793 }
1794
Christopher Tate043dadc2009-06-02 16:11:00 -07001795 // ----- Back up a set of applications via a worker thread -----
1796
Christopher Tate8e294d42011-08-31 20:37:12 -07001797 enum BackupState {
1798 INITIAL,
1799 RUNNING_QUEUE,
1800 FINAL
1801 }
1802
1803 class PerformBackupTask implements BackupRestoreTask {
1804 private static final String TAG = "PerformBackupTask";
1805
Christopher Tateaa088442009-06-16 18:25:46 -07001806 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001807 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001808 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001809 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001810 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001811 BackupState mCurrentState;
1812
1813 // carried information about the current in-flight operation
1814 PackageInfo mCurrentPackage;
1815 File mSavedStateName;
1816 File mBackupDataName;
1817 File mNewStateName;
1818 ParcelFileDescriptor mSavedState;
1819 ParcelFileDescriptor mBackupData;
1820 ParcelFileDescriptor mNewState;
1821 int mStatus;
1822 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001823
Christopher Tate44a27902010-01-27 17:15:49 -08001824 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001825 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001826 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001827 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001828 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001829
1830 try {
1831 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1832 } catch (RemoteException e) {
1833 // can't happen; the transport is local
1834 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001835
1836 mCurrentState = BackupState.INITIAL;
1837 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001838
1839 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001840 }
1841
Christopher Tate8e294d42011-08-31 20:37:12 -07001842 // Main entry point: perform one chunk of work, updating the state as appropriate
1843 // and reposting the next chunk to the primary backup handler thread.
1844 @Override
1845 public void execute() {
1846 switch (mCurrentState) {
1847 case INITIAL:
1848 beginBackup();
1849 break;
1850
1851 case RUNNING_QUEUE:
1852 invokeNextAgent();
1853 break;
1854
1855 case FINAL:
1856 if (!mFinished) finalizeBackup();
1857 else {
1858 Slog.e(TAG, "Duplicate finish");
1859 }
Christopher Tate2982d062011-09-06 20:35:24 -07001860 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001861 break;
1862 }
1863 }
1864
1865 // We're starting a backup pass. Initialize the transport and send
1866 // the PM metadata blob if we haven't already.
1867 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001868 if (DEBUG_BACKUP_TRACE) {
1869 clearBackupTrace();
1870 StringBuilder b = new StringBuilder(256);
1871 b.append("beginBackup: [");
1872 for (BackupRequest req : mOriginalQueue) {
1873 b.append(' ');
1874 b.append(req.packageName);
1875 }
1876 b.append(" ]");
1877 addBackupTrace(b.toString());
1878 }
1879
Christopher Tate8e294d42011-08-31 20:37:12 -07001880 mStatus = BackupConstants.TRANSPORT_OK;
1881
1882 // Sanity check: if the queue is empty we have no work to do.
1883 if (mOriginalQueue.isEmpty()) {
1884 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001885 addBackupTrace("queue empty at begin");
1886 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001887 return;
1888 }
1889
1890 // We need to retain the original queue contents in case of transport
1891 // failure, but we want a working copy that we can manipulate along
1892 // the way.
1893 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1894
Joe Onorato8a9b2202010-02-26 18:56:32 -08001895 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001896
Christopher Tate8e294d42011-08-31 20:37:12 -07001897 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001898 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001899 final String transportName = mTransport.transportDirName();
1900 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001901
Dan Egnor852f8e42009-09-30 11:20:45 -07001902 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001904 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001905 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001906 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001907 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001908
1909 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001910 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001911 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001912 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001913 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001914 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001915 }
Dan Egnor01445162009-09-21 17:04:05 -07001916 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001917
1918 // The package manager doesn't have a proper <application> etc, but since
1919 // it's running here in the system process we can just set up its agent
1920 // directly and use a synthetic BackupRequest. We always run this pass
1921 // because it's cheap and this way we guarantee that we don't get out of
1922 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001923 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001924 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1925 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001926 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001927 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001928 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001929 }
Christopher Tate90967f42009-09-20 15:28:33 -07001930
Christopher Tate8e294d42011-08-31 20:37:12 -07001931 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1932 // The backend reports that our dataset has been wiped. Note this in
1933 // the event log; the no-success code below will reset the backup
1934 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001935 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001936 }
1937 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001938 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001939 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001940 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001941 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001942 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1943 // metadata and its completion/timeout callback will continue the state
1944 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001945 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001946 if (mStatus != BackupConstants.TRANSPORT_OK) {
1947 // if things went wrong at this point, we need to
1948 // restage everything and try again later.
1949 resetBackupState(mStateDir); // Just to make sure.
1950 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001951 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001952 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001953 }
1954
Christopher Tate8e294d42011-08-31 20:37:12 -07001955 // Transport has been initialized and the PM metadata submitted successfully
1956 // if that was warranted. Now we process the single next thing in the queue.
1957 void invokeNextAgent() {
1958 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001959 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001960
Christopher Tate8e294d42011-08-31 20:37:12 -07001961 // Sanity check that we have work to do. If not, skip to the end where
1962 // we reestablish the wakelock invariants etc.
1963 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001964 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001965 executeNextState(BackupState.FINAL);
1966 return;
1967 }
1968
1969 // pop the entry we're going to process on this step
1970 BackupRequest request = mQueue.get(0);
1971 mQueue.remove(0);
1972
1973 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001974 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001975
1976 // Verify that the requested app exists; it might be something that
1977 // requested a backup but was then uninstalled. The request was
1978 // journalled and rather than tamper with the journal it's safer
1979 // to sanity-check here. This also gives us the classname of the
1980 // package's backup agent.
1981 try {
1982 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1983 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001984 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1985 // The manifest has changed but we had a stale backup request pending.
1986 // This won't happen again because the app won't be requesting further
1987 // backups.
1988 Slog.i(TAG, "Package " + request.packageName
1989 + " no longer supports backup; skipping");
1990 addBackupTrace("skipping - no agent, completion is noop");
1991 executeNextState(BackupState.RUNNING_QUEUE);
1992 return;
1993 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001994
Christopher Tate043dadc2009-06-02 16:11:00 -07001995 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001996 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1998 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001999 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002000 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07002001 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002002 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2003 // at this point we'll either get a completion callback from the
2004 // agent, or a timeout message on the main handler. either way, we're
2005 // done here as long as we're successful so far.
2006 } else {
2007 // Timeout waiting for the agent
2008 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002009 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002010 } catch (SecurityException ex) {
2011 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002012 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002013 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002014 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002015 }
2016 } catch (NameNotFoundException e) {
2017 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002018 addBackupTrace("no such package");
2019 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002020 } finally {
2021 mWakelock.setWorkSource(null);
2022
2023 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002024 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002025 if (mStatus != BackupConstants.TRANSPORT_OK) {
2026 BackupState nextState = BackupState.RUNNING_QUEUE;
2027
2028 // An agent-level failure means we reenqueue this one agent for
2029 // a later retry, but otherwise proceed normally.
2030 if (mStatus == BackupConstants.AGENT_ERROR) {
2031 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2032 + " - restaging");
2033 dataChangedImpl(request.packageName);
2034 mStatus = BackupConstants.TRANSPORT_OK;
2035 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002036 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2037 // Failed lookup of the app, so we couldn't bring up an agent, but
2038 // we're otherwise fine. Just drop it and go on to the next as usual.
2039 mStatus = BackupConstants.TRANSPORT_OK;
2040 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002041 // Transport-level failure means we reenqueue everything
2042 revertAndEndBackup();
2043 nextState = BackupState.FINAL;
2044 }
2045
2046 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002047 } else {
2048 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002049 }
2050 }
2051 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002052
Christopher Tate8e294d42011-08-31 20:37:12 -07002053 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002054 addBackupTrace("finishing");
2055
Christopher Tate8e294d42011-08-31 20:37:12 -07002056 // Either backup was successful, in which case we of course do not need
2057 // this pass's journal any more; or it failed, in which case we just
2058 // re-enqueued all of these packages in the current active journal.
2059 // Either way, we no longer need this pass's journal.
2060 if (mJournal != null && !mJournal.delete()) {
2061 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2062 }
2063
2064 // If everything actually went through and this is the first time we've
2065 // done a backup, we can now record what the current backup dataset token
2066 // is.
2067 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002068 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002069 try {
2070 mCurrentToken = mTransport.getCurrentRestoreSet();
2071 } catch (RemoteException e) {} // can't happen
2072 writeRestoreTokens();
2073 }
2074
Christopher Tate336a6492011-10-05 16:05:43 -07002075 // Set up the next backup pass - at this point we can set mBackupRunning
2076 // to false to allow another pass to fire, because we're done with the
2077 // state machine sequence and the wakelock is refcounted.
2078 synchronized (mQueueLock) {
2079 mBackupRunning = false;
2080 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002081 // Make sure we back up everything and perform the one-time init
2082 clearMetadata();
2083 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002084 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002085 backupNow();
2086 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002087 }
2088
2089 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002090 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002091 Slog.i(TAG, "Backup pass finished.");
2092 mWakelock.release();
2093 }
2094
Christopher Tatee659fb92011-10-10 16:34:50 -07002095 // Remove the PM metadata state. This will generate an init on the next pass.
2096 void clearMetadata() {
2097 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2098 if (pmState.exists()) pmState.delete();
2099 }
2100
Christopher Tate8e294d42011-08-31 20:37:12 -07002101 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2102 // handler in case it doesn't get back to us.
2103 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002104 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002105 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2106 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002107
Christopher Tate8e294d42011-08-31 20:37:12 -07002108 mSavedStateName = new File(mStateDir, packageName);
2109 mBackupDataName = new File(mDataDir, packageName + ".data");
2110 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111
Christopher Tate8e294d42011-08-31 20:37:12 -07002112 mSavedState = null;
2113 mBackupData = null;
2114 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002115
Christopher Tate4a627c72011-04-01 14:43:32 -07002116 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002117 try {
2118 // Look up the package info & signatures. This is first so that if it
2119 // throws an exception, there's no file setup yet that would need to
2120 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002121 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002122 // The metadata 'package' is synthetic; construct one and make
2123 // sure our global state is pointed at it
2124 mCurrentPackage = new PackageInfo();
2125 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002126 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127
Christopher Tatec7b31e32009-06-10 15:49:30 -07002128 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002129 // the saved-state "file". This is by definition an incremental,
2130 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002131 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002132 ParcelFileDescriptor.MODE_READ_ONLY |
2133 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002134
Christopher Tate8e294d42011-08-31 20:37:12 -07002135 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002136 ParcelFileDescriptor.MODE_READ_WRITE |
2137 ParcelFileDescriptor.MODE_CREATE |
2138 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002139
rpcraigebab0ae2012-12-04 09:37:23 -05002140 if (!SELinux.restorecon(mBackupDataName)) {
2141 Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2142 }
2143
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002145 ParcelFileDescriptor.MODE_READ_WRITE |
2146 ParcelFileDescriptor.MODE_CREATE |
2147 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002148
Christopher Tate44a27902010-01-27 17:15:49 -08002149 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002150 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002151 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002152 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002153 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002154 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002155 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002156 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002157 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2158 e.toString());
2159 agentErrorCleanup();
2160 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002161 }
2162
Christopher Tate8e294d42011-08-31 20:37:12 -07002163 // At this point the agent is off and running. The next thing to happen will
2164 // either be a callback from the agent, at which point we'll process its data
2165 // for transport, or a timeout. Either way the next phase will happen in
2166 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002167 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002168 return BackupConstants.TRANSPORT_OK;
2169 }
2170
2171 @Override
2172 public void operationComplete() {
2173 // Okay, the agent successfully reported back to us. Spin the data off to the
2174 // transport and proceed with the next stage.
2175 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2176 + mCurrentPackage.packageName);
2177 mBackupHandler.removeMessages(MSG_TIMEOUT);
2178 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002179 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002180
2181 ParcelFileDescriptor backupData = null;
2182 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002183 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002184 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002185 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002186 if (mStatus == BackupConstants.TRANSPORT_OK) {
2187 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002188 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002191 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002192
Dan Egnor83861e72009-09-17 16:17:55 -07002193 // TODO - We call finishBackup() for each application backed up, because
2194 // we need to know now whether it succeeded or failed. Instead, we should
2195 // hold off on finishBackup() until the end, which implies holding off on
2196 // renaming *all* the output state files (see below) until that happens.
2197
Christopher Tate6de74ff2012-01-17 15:20:32 -08002198 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002199 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002200 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002201 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002202 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002203 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002204 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002205 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002206 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002207 }
2208
2209 // After successful transport, delete the now-stale data
2210 // and juggle the files so that next time we supply the agent
2211 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002212 if (mStatus == BackupConstants.TRANSPORT_OK) {
2213 mBackupDataName.delete();
2214 mNewStateName.renameTo(mSavedStateName);
2215 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2216 mCurrentPackage.packageName, size);
2217 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002218 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002219 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2220 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002221 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002222 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002223 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2224 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2225 mCurrentPackage.packageName);
2226 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002227 } finally {
2228 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002229 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002230
Christopher Tate8e294d42011-08-31 20:37:12 -07002231 // If we encountered an error here it's a transport-level failure. That
2232 // means we need to halt everything and reschedule everything for next time.
2233 final BackupState nextState;
2234 if (mStatus != BackupConstants.TRANSPORT_OK) {
2235 revertAndEndBackup();
2236 nextState = BackupState.FINAL;
2237 } else {
2238 // Success! Proceed with the next app if any, otherwise we're done.
2239 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2240 }
2241
2242 executeNextState(nextState);
2243 }
2244
2245 @Override
2246 public void handleTimeout() {
2247 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2248 // it for the next time we run a backup pass.
2249 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2250 // fail repeatedly (i.e. have proved themselves to be buggy).
2251 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2252 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2253 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002254 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002255 agentErrorCleanup();
2256 dataChangedImpl(mCurrentPackage.packageName);
2257 }
2258
2259 void revertAndEndBackup() {
2260 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002261 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002262 for (BackupRequest request : mOriginalQueue) {
2263 dataChangedImpl(request.packageName);
2264 }
2265 // We also want to reset the backup schedule based on whatever
2266 // the transport suggests by way of retry/backoff time.
2267 restartBackupAlarm();
2268 }
2269
2270 void agentErrorCleanup() {
2271 mBackupDataName.delete();
2272 mNewStateName.delete();
2273 clearAgentState();
2274
2275 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2276 }
2277
2278 // Cleanup common to both success and failure cases
2279 void clearAgentState() {
2280 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2281 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2282 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2283 mSavedState = mBackupData = mNewState = null;
2284 synchronized (mCurrentOpLock) {
2285 mCurrentOperations.clear();
2286 }
2287
2288 // If this was a pseudopackage there's no associated Activity Manager state
2289 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002290 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002291 try { // unbind even on timeout, just in case
2292 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2293 } catch (RemoteException e) {}
2294 }
2295 }
2296
2297 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002298 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002299 synchronized (mQueueLock) {
2300 try {
2301 startBackupAlarmsLocked(mTransport.requestBackupTime());
2302 } catch (RemoteException e) { /* cannot happen */ }
2303 }
2304 }
2305
2306 void executeNextState(BackupState nextState) {
2307 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2308 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002309 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002310 mCurrentState = nextState;
2311 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2312 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002313 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002314 }
2315
Christopher Tatedf01dea2009-06-09 20:45:02 -07002316
Christopher Tate294b5122013-02-19 14:08:59 -08002317 // ----- Full backup/restore to a file/socket -----
Christopher Tate4a627c72011-04-01 14:43:32 -07002318
Christopher Tate294b5122013-02-19 14:08:59 -08002319 abstract class ObbServiceClient {
2320 public IObbBackupService mObbService;
2321 public void setObbBinder(IObbBackupService binder) {
2322 mObbService = binder;
2323 }
2324 }
2325
2326 class FullBackupObbConnection implements ServiceConnection {
2327 volatile IObbBackupService mService;
2328
2329 FullBackupObbConnection() {
2330 mService = null;
2331 }
2332
2333 public void establish() {
2334 if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2335 Intent obbIntent = new Intent().setComponent(new ComponentName(
2336 "com.android.sharedstoragebackup",
2337 "com.android.sharedstoragebackup.ObbBackupService"));
2338 BackupManagerService.this.mContext.bindService(
2339 obbIntent, this, Context.BIND_AUTO_CREATE);
2340 }
2341
2342 public void tearDown() {
2343 BackupManagerService.this.mContext.unbindService(this);
2344 }
2345
2346 public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2347 boolean success = false;
2348 waitForConnection();
2349
2350 ParcelFileDescriptor[] pipes = null;
2351 try {
2352 pipes = ParcelFileDescriptor.createPipe();
2353 int token = generateToken();
2354 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2355 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2356 routeSocketDataToOutput(pipes[0], out);
2357 success = waitUntilOperationComplete(token);
2358 } catch (Exception e) {
2359 Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2360 } finally {
2361 try {
2362 out.flush();
2363 if (pipes != null) {
2364 if (pipes[0] != null) pipes[0].close();
2365 if (pipes[1] != null) pipes[1].close();
2366 }
2367 } catch (IOException e) {
2368 Slog.w(TAG, "I/O error closing down OBB backup", e);
2369 }
2370 }
2371 return success;
2372 }
2373
2374 public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2375 long fileSize, int type, String path, long mode, long mtime,
2376 int token, IBackupManager callbackBinder) {
2377 waitForConnection();
2378
2379 try {
2380 mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2381 token, callbackBinder);
2382 } catch (Exception e) {
2383 Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2384 }
2385 }
2386
2387 private void waitForConnection() {
2388 synchronized (this) {
2389 while (mService == null) {
2390 if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2391 try {
2392 this.wait();
2393 } catch (InterruptedException e) { /* never interrupted */ }
2394 }
2395 if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2396 }
2397 }
2398
2399 @Override
2400 public void onServiceConnected(ComponentName name, IBinder service) {
2401 synchronized (this) {
2402 mService = IObbBackupService.Stub.asInterface(service);
2403 if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2404 + " connected on " + this);
2405 this.notifyAll();
2406 }
2407 }
2408
2409 @Override
2410 public void onServiceDisconnected(ComponentName name) {
2411 synchronized (this) {
2412 mService = null;
2413 if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2414 this.notifyAll();
2415 }
2416 }
2417
2418 }
2419
2420 private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2421 throws IOException {
2422 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2423 DataInputStream in = new DataInputStream(raw);
2424
2425 byte[] buffer = new byte[32 * 1024];
2426 int chunkTotal;
2427 while ((chunkTotal = in.readInt()) > 0) {
2428 while (chunkTotal > 0) {
2429 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2430 int nRead = in.read(buffer, 0, toRead);
2431 out.write(buffer, 0, nRead);
2432 chunkTotal -= nRead;
2433 }
2434 }
2435 }
2436
2437 class PerformFullBackupTask extends ObbServiceClient implements Runnable {
Christopher Tate4a627c72011-04-01 14:43:32 -07002438 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002439 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002440 IFullBackupRestoreObserver mObserver;
2441 boolean mIncludeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002442 boolean mIncludeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002443 boolean mIncludeShared;
2444 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002445 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002446 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002447 String mCurrentPassword;
2448 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002449 AtomicBoolean mLatchObject;
2450 File mFilesDir;
2451 File mManifestFile;
Christopher Tate294b5122013-02-19 14:08:59 -08002452
Christopher Tate4a627c72011-04-01 14:43:32 -07002453
Christopher Tate7926a692011-07-11 11:31:57 -07002454 class FullBackupRunner implements Runnable {
2455 PackageInfo mPackage;
2456 IBackupAgent mAgent;
2457 ParcelFileDescriptor mPipe;
2458 int mToken;
2459 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002460 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002461
2462 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002463 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002464 mPackage = pack;
2465 mAgent = agent;
2466 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2467 mToken = token;
2468 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002469 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002470 }
2471
2472 @Override
2473 public void run() {
2474 try {
2475 BackupDataOutput output = new BackupDataOutput(
2476 mPipe.getFileDescriptor());
2477
Christopher Tate73d73692012-01-20 17:11:31 -08002478 if (mWriteManifest) {
2479 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2480 writeAppManifest(mPackage, mManifestFile, mSendApk);
2481 FullBackup.backupToTar(mPackage.packageName, null, null,
2482 mFilesDir.getAbsolutePath(),
2483 mManifestFile.getAbsolutePath(),
2484 output);
2485 }
Christopher Tate7926a692011-07-11 11:31:57 -07002486
2487 if (mSendApk) {
2488 writeApkToBackup(mPackage, output);
2489 }
2490
Christopher Tatec58efa62011-08-01 19:20:14 -07002491 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002492 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002493 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2494 } catch (IOException e) {
2495 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2496 } catch (RemoteException e) {
2497 Slog.e(TAG, "Remote agent vanished during full backup of "
2498 + mPackage.packageName);
2499 } finally {
2500 try {
2501 mPipe.close();
2502 } catch (IOException e) {}
2503 }
2504 }
2505 }
2506
Christopher Tate4a627c72011-04-01 14:43:32 -07002507 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate294b5122013-02-19 14:08:59 -08002508 boolean includeApks, boolean includeObbs, boolean includeShared,
2509 String curPassword, String encryptPassword, boolean doAllApps,
2510 boolean doSystem, String[] packages, AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002511 mOutputFile = fd;
2512 mObserver = observer;
2513 mIncludeApks = includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002514 mIncludeObbs = includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002515 mIncludeShared = includeShared;
2516 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002517 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002518 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002519 mCurrentPassword = curPassword;
2520 // when backing up, if there is a current backup password, we require that
2521 // the user use a nonempty encryption password as well. if one is supplied
2522 // in the UI we use that, but if the UI was left empty we fall back to the
2523 // current backup password (which was supplied by the user as well).
2524 if (encryptPassword == null || "".equals(encryptPassword)) {
2525 mEncryptPassword = curPassword;
2526 } else {
2527 mEncryptPassword = encryptPassword;
2528 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002529 mLatchObject = latch;
2530
2531 mFilesDir = new File("/data/system");
2532 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2533 }
2534
2535 @Override
2536 public void run() {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002537 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate294b5122013-02-19 14:08:59 -08002538
2539 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
2540 FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2541 obbConnection.establish(); // we'll want this later
2542
Christopher Tate4a627c72011-04-01 14:43:32 -07002543 sendStartBackup();
2544
2545 // doAllApps supersedes the package set if any
2546 if (mAllApps) {
2547 packagesToBackup = mPackageManager.getInstalledPackages(
2548 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002549 // Exclude system apps if we've been asked to do so
2550 if (mIncludeSystem == false) {
2551 for (int i = 0; i < packagesToBackup.size(); ) {
2552 PackageInfo pkg = packagesToBackup.get(i);
2553 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2554 packagesToBackup.remove(i);
2555 } else {
2556 i++;
2557 }
2558 }
2559 }
2560 }
2561
2562 // Now process the command line argument packages, if any. Note that explicitly-
2563 // named system-partition packages will be included even if includeSystem was
2564 // set to false.
2565 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002566 for (String pkgName : mPackages) {
2567 try {
2568 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2569 PackageManager.GET_SIGNATURES));
2570 } catch (NameNotFoundException e) {
2571 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2572 }
2573 }
2574 }
2575
Christopher Tate73d73692012-01-20 17:11:31 -08002576 // Cull any packages that have indicated that backups are not permitted, as well
2577 // as any explicit mention of the 'special' shared-storage agent package (we
2578 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002579 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002580 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002581 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2582 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002583 packagesToBackup.remove(i);
2584 } else {
2585 i++;
2586 }
2587 }
2588
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002589 // Cull any packages that run as system-domain uids but do not define their
2590 // own backup agents
2591 for (int i = 0; i < packagesToBackup.size(); ) {
2592 PackageInfo pkg = packagesToBackup.get(i);
2593 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2594 && (pkg.applicationInfo.backupAgentName == null)) {
2595 if (MORE_DEBUG) {
2596 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2597 }
2598 packagesToBackup.remove(i);
2599 } else {
2600 i++;
2601 }
2602 }
2603
Christopher Tate7926a692011-07-11 11:31:57 -07002604 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002605 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002606
Christopher Tate4a627c72011-04-01 14:43:32 -07002607 PackageInfo pkg = null;
2608 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002609 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002610 boolean compressing = COMPRESS_FULL_BACKUPS;
2611 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002612
Christopher Tateeef4ae42011-08-05 13:15:53 -07002613 // Verify that the given password matches the currently-active
2614 // backup password, if any
2615 if (hasBackupPassword()) {
2616 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2617 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2618 return;
2619 }
2620 }
2621
Christopher Tate7bdb0962011-07-13 19:30:21 -07002622 // Write the global file header. All strings are UTF-8 encoded; lines end
2623 // with a '\n' byte. Actual backup data begins immediately following the
2624 // final '\n'.
2625 //
2626 // line 1: "ANDROID BACKUP"
2627 // line 2: backup file format version, currently "1"
2628 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002629 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2630 //
2631 // When line 4 is not "none", then additional header data follows:
2632 //
2633 // line 5: user password salt [hex]
2634 // line 6: master key checksum salt [hex]
2635 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2636 // line 8: IV of the user key [hex]
2637 // line 9: master key blob [hex]
2638 // IV of the master key, master key itself, master key checksum hash
2639 //
2640 // The master key checksum is the master key plus its checksum salt, run through
2641 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2642 // correct password for decrypting the archive: the master key decrypted from
2643 // the archive using the user-supplied password is also run through PBKDF2 in
2644 // this way, and if the result does not match the checksum as stored in the
2645 // archive, then we know that the user-supplied password does not match the
2646 // archive's.
2647 StringBuilder headerbuf = new StringBuilder(1024);
2648
Christopher Tate7bdb0962011-07-13 19:30:21 -07002649 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002650 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2651 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002652
2653 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002654 // Set up the encryption stage if appropriate, and emit the correct header
2655 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002656 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2657 } else {
2658 headerbuf.append("none\n");
2659 }
2660
Christopher Tate7bdb0962011-07-13 19:30:21 -07002661 byte[] header = headerbuf.toString().getBytes("UTF-8");
2662 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002663
2664 // Set up the compression stage feeding into the encryption stage (if any)
2665 if (compressing) {
2666 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2667 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2668 }
2669
2670 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002671 } catch (Exception e) {
2672 // Should never happen!
2673 Slog.e(TAG, "Unable to emit archive header", e);
2674 return;
2675 }
2676
Christopher Tate73d73692012-01-20 17:11:31 -08002677 // Shared storage if requested
2678 if (mIncludeShared) {
2679 try {
2680 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2681 packagesToBackup.add(pkg);
2682 } catch (NameNotFoundException e) {
2683 Slog.e(TAG, "Unable to find shared-storage backup handler");
2684 }
2685 }
2686
Christopher Tateb0628bf2011-06-02 15:08:13 -07002687 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002688 int N = packagesToBackup.size();
2689 for (int i = 0; i < N; i++) {
2690 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002691 backupOnePackage(pkg, out);
Christopher Tate294b5122013-02-19 14:08:59 -08002692
2693 // after the app's agent runs to handle its private filesystem
2694 // contents, back up any OBB content it has on its behalf.
2695 if (mIncludeObbs) {
2696 boolean obbOkay = obbConnection.backupObbs(pkg, out);
2697 if (!obbOkay) {
2698 throw new RuntimeException("Failure writing OBB stack for " + pkg);
2699 }
2700 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002701 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002702
Christopher Tate6853fcf2011-08-10 17:52:21 -07002703 // Done!
2704 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002705 } catch (RemoteException e) {
2706 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002707 } catch (Exception e) {
2708 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002709 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002710 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002711 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002712 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002713 mOutputFile.close();
2714 } catch (IOException e) {
2715 /* nothing we can do about this */
2716 }
2717 synchronized (mCurrentOpLock) {
2718 mCurrentOperations.clear();
2719 }
2720 synchronized (mLatchObject) {
2721 mLatchObject.set(true);
2722 mLatchObject.notifyAll();
2723 }
2724 sendEndBackup();
Christopher Tate294b5122013-02-19 14:08:59 -08002725 obbConnection.tearDown();
Christopher Tate4a627c72011-04-01 14:43:32 -07002726 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002727 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002728 }
2729 }
2730
Christopher Tate2efd2db2011-07-19 16:32:49 -07002731 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2732 OutputStream ofstream) throws Exception {
2733 // User key will be used to encrypt the master key.
2734 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002735 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002736 PBKDF2_HASH_ROUNDS);
2737
2738 // the master key is random for each backup
2739 byte[] masterPw = new byte[256 / 8];
2740 mRng.nextBytes(masterPw);
2741 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2742
2743 // primary encryption of the datastream with the random key
2744 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2745 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2746 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2747 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2748
2749 // line 4: name of encryption algorithm
2750 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2751 headerbuf.append('\n');
2752 // line 5: user password salt [hex]
2753 headerbuf.append(byteArrayToHex(newUserSalt));
2754 headerbuf.append('\n');
2755 // line 6: master key checksum salt [hex]
2756 headerbuf.append(byteArrayToHex(checksumSalt));
2757 headerbuf.append('\n');
2758 // line 7: number of PBKDF2 rounds used [decimal]
2759 headerbuf.append(PBKDF2_HASH_ROUNDS);
2760 headerbuf.append('\n');
2761
2762 // line 8: IV of the user key [hex]
2763 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2764 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2765
2766 byte[] IV = mkC.getIV();
2767 headerbuf.append(byteArrayToHex(IV));
2768 headerbuf.append('\n');
2769
2770 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2771 // [byte] IV length = Niv
2772 // [array of Niv bytes] IV itself
2773 // [byte] master key length = Nmk
2774 // [array of Nmk bytes] master key itself
2775 // [byte] MK checksum hash length = Nck
2776 // [array of Nck bytes] master key checksum hash
2777 //
2778 // The checksum is the (master key + checksum salt), run through the
2779 // stated number of PBKDF2 rounds
2780 IV = c.getIV();
2781 byte[] mk = masterKeySpec.getEncoded();
2782 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2783 checksumSalt, PBKDF2_HASH_ROUNDS);
2784
2785 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2786 + checksum.length + 3);
2787 DataOutputStream mkOut = new DataOutputStream(blob);
2788 mkOut.writeByte(IV.length);
2789 mkOut.write(IV);
2790 mkOut.writeByte(mk.length);
2791 mkOut.write(mk);
2792 mkOut.writeByte(checksum.length);
2793 mkOut.write(checksum);
2794 mkOut.flush();
2795 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2796 headerbuf.append(byteArrayToHex(encryptedMk));
2797 headerbuf.append('\n');
2798
2799 return finalOutput;
2800 }
2801
2802 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002803 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002804 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2805
2806 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2807 IApplicationThread.BACKUP_MODE_FULL);
2808 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002809 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002810 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002811 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002812
Christopher Tateb0628bf2011-06-02 15:08:13 -07002813 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002814 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002815 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002816 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002817 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2818 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2819 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2820
Christopher Tate73d73692012-01-20 17:11:31 -08002821 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002822
Christopher Tate7926a692011-07-11 11:31:57 -07002823 final int token = generateToken();
2824 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002825 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002826 pipes[1].close(); // the runner has dup'd it
2827 pipes[1] = null;
2828 Thread t = new Thread(runner);
2829 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002830
Christopher Tate7926a692011-07-11 11:31:57 -07002831 // Now pull data from the app and stuff it into the compressor
2832 try {
Christopher Tate294b5122013-02-19 14:08:59 -08002833 routeSocketDataToOutput(pipes[0], out);
Christopher Tate7926a692011-07-11 11:31:57 -07002834 } catch (IOException e) {
2835 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002836 }
2837
Christopher Tateb0628bf2011-06-02 15:08:13 -07002838 if (!waitUntilOperationComplete(token)) {
2839 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2840 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002841 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002842 }
Christopher Tate7926a692011-07-11 11:31:57 -07002843
Christopher Tateb0628bf2011-06-02 15:08:13 -07002844 } catch (IOException e) {
2845 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002846 } finally {
2847 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002848 // flush after every package
2849 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002850 if (pipes != null) {
2851 if (pipes[0] != null) pipes[0].close();
2852 if (pipes[1] != null) pipes[1].close();
2853 }
Christopher Tate7926a692011-07-11 11:31:57 -07002854 } catch (IOException e) {
2855 Slog.w(TAG, "Error bringing down backup stack");
2856 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002857 }
2858 } else {
2859 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2860 }
2861 tearDown(pkg);
2862 }
2863
Christopher Tate79ec80d2011-06-24 14:58:49 -07002864 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2865 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2866 final String appSourceDir = pkg.applicationInfo.sourceDir;
2867 final String apkDir = new File(appSourceDir).getParent();
2868 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2869 apkDir, appSourceDir, output);
2870
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002871 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2872 // doesn't have access to external storage.
2873
Christopher Tate79ec80d2011-06-24 14:58:49 -07002874 // Save associated .obb content if it exists and we did save the apk
2875 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002876 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002877 final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
Christopher Tate79ec80d2011-06-24 14:58:49 -07002878 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002879 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002880 File[] obbFiles = obbDir.listFiles();
2881 if (obbFiles != null) {
2882 final String obbDirName = obbDir.getAbsolutePath();
2883 for (File obb : obbFiles) {
2884 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2885 obbDirName, obb.getAbsolutePath(), output);
2886 }
2887 }
2888 }
2889 }
2890
Christopher Tate6853fcf2011-08-10 17:52:21 -07002891 private void finalizeBackup(OutputStream out) {
2892 try {
2893 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2894 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2895 out.write(eof);
2896 } catch (IOException e) {
2897 Slog.w(TAG, "Error attempting to finalize backup stream");
2898 }
2899 }
2900
Christopher Tate4a627c72011-04-01 14:43:32 -07002901 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2902 throws IOException {
2903 // Manifest format. All data are strings ending in LF:
2904 // BACKUP_MANIFEST_VERSION, currently 1
2905 //
2906 // Version 1:
2907 // package name
2908 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002909 // platform versionCode
2910 // getInstallerPackageName() for this package (maybe empty)
2911 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002912 // number of signatures == N
2913 // N*: signature byte array in ascii format per Signature.toCharsString()
2914 StringBuilder builder = new StringBuilder(4096);
2915 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2916
2917 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2918 printer.println(pkg.packageName);
2919 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002920 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2921
2922 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2923 printer.println((installerName != null) ? installerName : "");
2924
Christopher Tate4a627c72011-04-01 14:43:32 -07002925 printer.println(withApk ? "1" : "0");
2926 if (pkg.signatures == null) {
2927 printer.println("0");
2928 } else {
2929 printer.println(Integer.toString(pkg.signatures.length));
2930 for (Signature sig : pkg.signatures) {
2931 printer.println(sig.toCharsString());
2932 }
2933 }
2934
2935 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002936 outstream.write(builder.toString().getBytes());
2937 outstream.close();
2938 }
2939
2940 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002941 if (pkg != null) {
2942 final ApplicationInfo app = pkg.applicationInfo;
2943 if (app != null) {
2944 try {
2945 // unbind and tidy up even on timeout or failure, just in case
2946 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002947
Christopher Tateb0628bf2011-06-02 15:08:13 -07002948 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002949 if (app.uid != Process.SYSTEM_UID
2950 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002951 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002952 mActivityManager.killApplicationProcess(app.processName, app.uid);
2953 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002954 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002955 }
2956 } catch (RemoteException e) {
2957 Slog.d(TAG, "Lost app trying to shut down");
2958 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002959 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002960 }
2961 }
2962
2963 // wrappers for observer use
2964 void sendStartBackup() {
2965 if (mObserver != null) {
2966 try {
2967 mObserver.onStartBackup();
2968 } catch (RemoteException e) {
2969 Slog.w(TAG, "full backup observer went away: startBackup");
2970 mObserver = null;
2971 }
2972 }
2973 }
2974
2975 void sendOnBackupPackage(String name) {
2976 if (mObserver != null) {
2977 try {
2978 // TODO: use a more user-friendly name string
2979 mObserver.onBackupPackage(name);
2980 } catch (RemoteException e) {
2981 Slog.w(TAG, "full backup observer went away: backupPackage");
2982 mObserver = null;
2983 }
2984 }
2985 }
2986
2987 void sendEndBackup() {
2988 if (mObserver != null) {
2989 try {
2990 mObserver.onEndBackup();
2991 } catch (RemoteException e) {
2992 Slog.w(TAG, "full backup observer went away: endBackup");
2993 mObserver = null;
2994 }
2995 }
2996 }
2997 }
2998
2999
Christopher Tate75a99702011-05-18 16:28:19 -07003000 // ----- Full restore from a file/socket -----
3001
3002 // Description of a file in the restore datastream
3003 static class FileMetadata {
3004 String packageName; // name of the owning app
3005 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07003006 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07003007 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
3008 String path; // subpath within the semantic domain
3009 long mode; // e.g. 0666 (actually int)
3010 long mtime; // last mod time, UTC time_t (actually int)
3011 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003012
3013 @Override
3014 public String toString() {
3015 StringBuilder sb = new StringBuilder(128);
3016 sb.append("FileMetadata{");
3017 sb.append(packageName); sb.append(',');
3018 sb.append(type); sb.append(',');
3019 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3020 sb.append(size);
3021 sb.append('}');
3022 return sb.toString();
3023 }
Christopher Tate75a99702011-05-18 16:28:19 -07003024 }
3025
3026 enum RestorePolicy {
3027 IGNORE,
3028 ACCEPT,
3029 ACCEPT_IF_APK
3030 }
3031
Christopher Tate294b5122013-02-19 14:08:59 -08003032 class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
Christopher Tate75a99702011-05-18 16:28:19 -07003033 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07003034 String mCurrentPassword;
3035 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003036 IFullBackupRestoreObserver mObserver;
3037 AtomicBoolean mLatchObject;
3038 IBackupAgent mAgent;
3039 String mAgentPackage;
3040 ApplicationInfo mTargetApp;
Christopher Tate294b5122013-02-19 14:08:59 -08003041 FullBackupObbConnection mObbConnection = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003042 ParcelFileDescriptor[] mPipes = null;
3043
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003044 long mBytes;
3045
Christopher Tate75a99702011-05-18 16:28:19 -07003046 // possible handling states for a given package in the restore dataset
3047 final HashMap<String, RestorePolicy> mPackagePolicies
3048 = new HashMap<String, RestorePolicy>();
3049
3050 // installer package names for each encountered app, derived from the manifests
3051 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3052
3053 // Signatures for a given package found in its manifest file
3054 final HashMap<String, Signature[]> mManifestSignatures
3055 = new HashMap<String, Signature[]>();
3056
3057 // Packages we've already wiped data on when restoring their first file
3058 final HashSet<String> mClearedPackages = new HashSet<String>();
3059
Christopher Tate728a1c42011-07-28 18:03:03 -07003060 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003061 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07003062 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07003063 mCurrentPassword = curPassword;
3064 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003065 mObserver = observer;
3066 mLatchObject = latch;
3067 mAgent = null;
3068 mAgentPackage = null;
3069 mTargetApp = null;
Christopher Tate294b5122013-02-19 14:08:59 -08003070 mObbConnection = new FullBackupObbConnection();
Christopher Tate75a99702011-05-18 16:28:19 -07003071
3072 // Which packages we've already wiped data on. We prepopulate this
3073 // with a whitelist of packages known to be unclearable.
3074 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07003075 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07003076
Christopher Tate75a99702011-05-18 16:28:19 -07003077 }
3078
3079 class RestoreFileRunnable implements Runnable {
3080 IBackupAgent mAgent;
3081 FileMetadata mInfo;
3082 ParcelFileDescriptor mSocket;
3083 int mToken;
3084
3085 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3086 ParcelFileDescriptor socket, int token) throws IOException {
3087 mAgent = agent;
3088 mInfo = info;
3089 mToken = token;
3090
3091 // This class is used strictly for process-local binder invocations. The
3092 // semantics of ParcelFileDescriptor differ in this case; in particular, we
3093 // do not automatically get a 'dup'ed descriptor that we can can continue
3094 // to use asynchronously from the caller. So, we make sure to dup it ourselves
3095 // before proceeding to do the restore.
3096 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3097 }
3098
3099 @Override
3100 public void run() {
3101 try {
3102 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3103 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3104 mToken, mBackupManagerBinder);
3105 } catch (RemoteException e) {
3106 // never happens; this is used strictly for local binder calls
3107 }
3108 }
3109 }
3110
3111 @Override
3112 public void run() {
3113 Slog.i(TAG, "--- Performing full-dataset restore ---");
Christopher Tate294b5122013-02-19 14:08:59 -08003114 mObbConnection.establish();
Christopher Tate75a99702011-05-18 16:28:19 -07003115 sendStartRestore();
3116
Christopher Tateb0628bf2011-06-02 15:08:13 -07003117 // Are we able to restore shared-storage data?
3118 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08003119 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07003120 }
3121
Christopher Tate2efd2db2011-07-19 16:32:49 -07003122 FileInputStream rawInStream = null;
3123 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003124 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07003125 if (hasBackupPassword()) {
3126 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
3127 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3128 return;
3129 }
3130 }
3131
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003132 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003133 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003134 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3135 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003136
3137 // First, parse out the unencrypted/uncompressed header
3138 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003139 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003140 final InputStream in;
3141
3142 boolean okay = false;
3143 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3144 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003145 rawDataIn.readFully(streamHeader);
3146 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3147 if (Arrays.equals(magicBytes, streamHeader)) {
3148 // okay, header looks good. now parse out the rest of the fields.
3149 String s = readHeaderLine(rawInStream);
3150 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3151 // okay, it's a version we recognize
3152 s = readHeaderLine(rawInStream);
3153 compressed = (Integer.parseInt(s) != 0);
3154 s = readHeaderLine(rawInStream);
3155 if (s.equals("none")) {
3156 // no more header to parse; we're good to go
3157 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003158 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003159 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3160 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003161 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003162 }
3163 } else Slog.w(TAG, "Archive is encrypted but no password given");
3164 } else Slog.w(TAG, "Wrong header version: " + s);
3165 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003166
3167 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003168 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003169 return;
3170 }
3171
3172 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003173 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003174
3175 boolean didRestore;
3176 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003177 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003178 } while (didRestore);
3179
Christopher Tatec58efa62011-08-01 19:20:14 -07003180 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003181 } catch (IOException e) {
3182 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003183 } finally {
3184 tearDownPipes();
3185 tearDownAgent(mTargetApp);
3186
3187 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003188 if (rawDataIn != null) rawDataIn.close();
3189 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003190 mInputFile.close();
3191 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003192 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003193 /* nothing we can do about this */
3194 }
3195 synchronized (mCurrentOpLock) {
3196 mCurrentOperations.clear();
3197 }
3198 synchronized (mLatchObject) {
3199 mLatchObject.set(true);
3200 mLatchObject.notifyAll();
3201 }
Christopher Tate294b5122013-02-19 14:08:59 -08003202 mObbConnection.tearDown();
Christopher Tate75a99702011-05-18 16:28:19 -07003203 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003204 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003205 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003206 }
3207 }
3208
Christopher Tate7bdb0962011-07-13 19:30:21 -07003209 String readHeaderLine(InputStream in) throws IOException {
3210 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003211 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003212 while ((c = in.read()) >= 0) {
3213 if (c == '\n') break; // consume and discard the newlines
3214 buffer.append((char)c);
3215 }
3216 return buffer.toString();
3217 }
3218
Christopher Tate2efd2db2011-07-19 16:32:49 -07003219 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3220 InputStream result = null;
3221 try {
3222 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3223
3224 String userSaltHex = readHeaderLine(rawInStream); // 5
3225 byte[] userSalt = hexToByteArray(userSaltHex);
3226
3227 String ckSaltHex = readHeaderLine(rawInStream); // 6
3228 byte[] ckSalt = hexToByteArray(ckSaltHex);
3229
3230 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3231 String userIvHex = readHeaderLine(rawInStream); // 8
3232
3233 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3234
3235 // decrypt the master key blob
3236 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003237 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003238 rounds);
3239 byte[] IV = hexToByteArray(userIvHex);
3240 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3241 c.init(Cipher.DECRYPT_MODE,
3242 new SecretKeySpec(userKey.getEncoded(), "AES"),
3243 ivSpec);
3244 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3245 byte[] mkBlob = c.doFinal(mkCipher);
3246
3247 // first, the master key IV
3248 int offset = 0;
3249 int len = mkBlob[offset++];
3250 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3251 offset += len;
3252 // then the master key itself
3253 len = mkBlob[offset++];
3254 byte[] mk = Arrays.copyOfRange(mkBlob,
3255 offset, offset + len);
3256 offset += len;
3257 // and finally the master key checksum hash
3258 len = mkBlob[offset++];
3259 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3260 offset, offset + len);
3261
3262 // now validate the decrypted master key against the checksum
3263 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3264 if (Arrays.equals(calculatedCk, mkChecksum)) {
3265 ivSpec = new IvParameterSpec(IV);
3266 c.init(Cipher.DECRYPT_MODE,
3267 new SecretKeySpec(mk, "AES"),
3268 ivSpec);
3269 // Only if all of the above worked properly will 'result' be assigned
3270 result = new CipherInputStream(rawInStream, c);
3271 } else Slog.w(TAG, "Incorrect password");
3272 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3273 } catch (InvalidAlgorithmParameterException e) {
3274 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3275 } catch (BadPaddingException e) {
3276 // This case frequently occurs when the wrong password is used to decrypt
3277 // the master key. Use the identical "incorrect password" log text as is
3278 // used in the checksum failure log in order to avoid providing additional
3279 // information to an attacker.
3280 Slog.w(TAG, "Incorrect password");
3281 } catch (IllegalBlockSizeException e) {
3282 Slog.w(TAG, "Invalid block size in master key");
3283 } catch (NoSuchAlgorithmException e) {
3284 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3285 } catch (NoSuchPaddingException e) {
3286 Slog.e(TAG, "Needed padding mechanism unavailable!");
3287 } catch (InvalidKeyException e) {
3288 Slog.w(TAG, "Illegal password; aborting");
3289 } catch (NumberFormatException e) {
3290 Slog.w(TAG, "Can't parse restore data header");
3291 } catch (IOException e) {
3292 Slog.w(TAG, "Can't read input header");
3293 }
3294
3295 return result;
3296 }
3297
Christopher Tate75a99702011-05-18 16:28:19 -07003298 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3299 FileMetadata info;
3300 try {
3301 info = readTarHeaders(instream);
3302 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003303 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003304 dumpFileMetadata(info);
3305 }
3306
3307 final String pkg = info.packageName;
3308 if (!pkg.equals(mAgentPackage)) {
3309 // okay, change in package; set up our various
3310 // bookkeeping if we haven't seen it yet
3311 if (!mPackagePolicies.containsKey(pkg)) {
3312 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3313 }
3314
3315 // Clean up the previous agent relationship if necessary,
3316 // and let the observer know we're considering a new app.
3317 if (mAgent != null) {
3318 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3319 tearDownPipes();
3320 tearDownAgent(mTargetApp);
3321 mTargetApp = null;
3322 mAgentPackage = null;
3323 }
3324 }
3325
3326 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3327 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3328 mPackageInstallers.put(pkg, info.installerPackageName);
3329 // We've read only the manifest content itself at this point,
3330 // so consume the footer before looping around to the next
3331 // input file
3332 skipTarPadding(info.size, instream);
3333 sendOnRestorePackage(pkg);
3334 } else {
3335 // Non-manifest, so it's actual file data. Is this a package
3336 // we're ignoring?
3337 boolean okay = true;
3338 RestorePolicy policy = mPackagePolicies.get(pkg);
3339 switch (policy) {
3340 case IGNORE:
3341 okay = false;
3342 break;
3343
3344 case ACCEPT_IF_APK:
3345 // If we're in accept-if-apk state, then the first file we
3346 // see MUST be the apk.
3347 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3348 if (DEBUG) Slog.d(TAG, "APK file; installing");
3349 // Try to install the app.
3350 String installerName = mPackageInstallers.get(pkg);
3351 okay = installApk(info, installerName, instream);
3352 // good to go; promote to ACCEPT
3353 mPackagePolicies.put(pkg, (okay)
3354 ? RestorePolicy.ACCEPT
3355 : RestorePolicy.IGNORE);
3356 // At this point we've consumed this file entry
3357 // ourselves, so just strip the tar footer and
3358 // go on to the next file in the input stream
3359 skipTarPadding(info.size, instream);
3360 return true;
3361 } else {
3362 // File data before (or without) the apk. We can't
3363 // handle it coherently in this case so ignore it.
3364 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3365 okay = false;
3366 }
3367 break;
3368
3369 case ACCEPT:
3370 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3371 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3372 // we can take the data without the apk, so we
3373 // *want* to do so. skip the apk by declaring this
3374 // one file not-okay without changing the restore
3375 // policy for the package.
3376 okay = false;
3377 }
3378 break;
3379
3380 default:
3381 // Something has gone dreadfully wrong when determining
3382 // the restore policy from the manifest. Ignore the
3383 // rest of this package's data.
3384 Slog.e(TAG, "Invalid policy from manifest");
3385 okay = false;
3386 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3387 break;
3388 }
3389
3390 // If the policy is satisfied, go ahead and set up to pipe the
3391 // data to the agent.
3392 if (DEBUG && okay && mAgent != null) {
3393 Slog.i(TAG, "Reusing existing agent instance");
3394 }
3395 if (okay && mAgent == null) {
3396 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3397
3398 try {
3399 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3400
3401 // If we haven't sent any data to this app yet, we probably
3402 // need to clear it first. Check that.
3403 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003404 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003405 // responsible for coherently managing a full
3406 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003407 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003408 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3409 clearApplicationDataSynchronous(pkg);
3410 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003411 if (DEBUG) Slog.d(TAG, "backup agent ("
3412 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003413 }
3414 mClearedPackages.add(pkg);
3415 } else {
3416 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3417 }
3418
3419 // All set; now set up the IPC and launch the agent
3420 setUpPipes();
3421 mAgent = bindToAgentSynchronous(mTargetApp,
3422 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3423 mAgentPackage = pkg;
3424 } catch (IOException e) {
3425 // fall through to error handling
3426 } catch (NameNotFoundException e) {
3427 // fall through to error handling
3428 }
3429
3430 if (mAgent == null) {
3431 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3432 okay = false;
3433 tearDownPipes();
3434 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3435 }
3436 }
3437
3438 // Sanity check: make sure we never give data to the wrong app. This
3439 // should never happen but a little paranoia here won't go amiss.
3440 if (okay && !pkg.equals(mAgentPackage)) {
3441 Slog.e(TAG, "Restoring data for " + pkg
3442 + " but agent is for " + mAgentPackage);
3443 okay = false;
3444 }
3445
3446 // At this point we have an agent ready to handle the full
3447 // restore data as well as a pipe for sending data to
3448 // that agent. Tell the agent to start reading from the
3449 // pipe.
3450 if (okay) {
3451 boolean agentSuccess = true;
3452 long toCopy = info.size;
3453 final int token = generateToken();
3454 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07003455 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate294b5122013-02-19 14:08:59 -08003456 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3457 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3458 + " : " + info.path);
3459 mObbConnection.restoreObbFile(pkg, mPipes[0],
3460 info.size, info.type, info.path, info.mode,
3461 info.mtime, token, mBackupManagerBinder);
Christopher Tate75a99702011-05-18 16:28:19 -07003462 } else {
Christopher Tate294b5122013-02-19 14:08:59 -08003463 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3464 + info.path);
3465 // fire up the app's agent listening on the socket. If
3466 // the agent is running in the system process we can't
3467 // just invoke it asynchronously, so we provide a thread
3468 // for it here.
3469 if (mTargetApp.processName.equals("system")) {
3470 Slog.d(TAG, "system process agent - spinning a thread");
3471 RestoreFileRunnable runner = new RestoreFileRunnable(
3472 mAgent, info, mPipes[0], token);
3473 new Thread(runner).start();
3474 } else {
3475 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3476 info.domain, info.path, info.mode, info.mtime,
3477 token, mBackupManagerBinder);
3478 }
Christopher Tate75a99702011-05-18 16:28:19 -07003479 }
3480 } catch (IOException e) {
3481 // couldn't dup the socket for a process-local restore
3482 Slog.d(TAG, "Couldn't establish restore");
3483 agentSuccess = false;
3484 okay = false;
3485 } catch (RemoteException e) {
Christopher Tate294b5122013-02-19 14:08:59 -08003486 // whoops, remote entity went away. We'll eat the content
Christopher Tate75a99702011-05-18 16:28:19 -07003487 // ourselves, then, and not copy it over.
3488 Slog.e(TAG, "Agent crashed during full restore");
3489 agentSuccess = false;
3490 okay = false;
3491 }
3492
3493 // Copy over the data if the agent is still good
3494 if (okay) {
3495 boolean pipeOkay = true;
3496 FileOutputStream pipe = new FileOutputStream(
3497 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003498 while (toCopy > 0) {
3499 int toRead = (toCopy > buffer.length)
3500 ? buffer.length : (int)toCopy;
3501 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003502 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003503 if (nRead <= 0) break;
3504 toCopy -= nRead;
3505
3506 // send it to the output pipe as long as things
3507 // are still good
3508 if (pipeOkay) {
3509 try {
3510 pipe.write(buffer, 0, nRead);
3511 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003512 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003513 pipeOkay = false;
3514 }
3515 }
3516 }
3517
3518 // done sending that file! Now we just need to consume
3519 // the delta from info.size to the end of block.
3520 skipTarPadding(info.size, instream);
3521
3522 // and now that we've sent it all, wait for the remote
3523 // side to acknowledge receipt
3524 agentSuccess = waitUntilOperationComplete(token);
3525 }
3526
3527 // okay, if the remote end failed at any point, deal with
3528 // it by ignoring the rest of the restore on it
3529 if (!agentSuccess) {
3530 mBackupHandler.removeMessages(MSG_TIMEOUT);
3531 tearDownPipes();
3532 tearDownAgent(mTargetApp);
3533 mAgent = null;
3534 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3535 }
3536 }
3537
3538 // Problems setting up the agent communication, or an already-
3539 // ignored package: skip to the next tar stream entry by
3540 // reading and discarding this file.
3541 if (!okay) {
3542 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3543 long bytesToConsume = (info.size + 511) & ~511;
3544 while (bytesToConsume > 0) {
3545 int toRead = (bytesToConsume > buffer.length)
3546 ? buffer.length : (int)bytesToConsume;
3547 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003548 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003549 if (nRead <= 0) break;
3550 bytesToConsume -= nRead;
3551 }
3552 }
3553 }
3554 }
3555 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003556 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003557 // treat as EOF
3558 info = null;
3559 }
3560
3561 return (info != null);
3562 }
3563
3564 void setUpPipes() throws IOException {
3565 mPipes = ParcelFileDescriptor.createPipe();
3566 }
3567
3568 void tearDownPipes() {
3569 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003570 try {
3571 mPipes[0].close();
3572 mPipes[0] = null;
3573 mPipes[1].close();
3574 mPipes[1] = null;
3575 } catch (IOException e) {
3576 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003577 }
3578 mPipes = null;
3579 }
3580 }
3581
3582 void tearDownAgent(ApplicationInfo app) {
3583 if (mAgent != null) {
3584 try {
3585 // unbind and tidy up even on timeout or failure, just in case
3586 mActivityManager.unbindBackupAgent(app);
3587
3588 // The agent was running with a stub Application object, so shut it down.
3589 // !!! We hardcode the confirmation UI's package name here rather than use a
3590 // manifest flag! TODO something less direct.
3591 if (app.uid != Process.SYSTEM_UID
3592 && !app.packageName.equals("com.android.backupconfirm")) {
3593 if (DEBUG) Slog.d(TAG, "Killing host process");
3594 mActivityManager.killApplicationProcess(app.processName, app.uid);
3595 } else {
3596 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3597 }
3598 } catch (RemoteException e) {
3599 Slog.d(TAG, "Lost app trying to shut down");
3600 }
3601 mAgent = null;
3602 }
3603 }
3604
3605 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3606 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003607 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003608 int mResult;
3609
3610 public void reset() {
3611 synchronized (mDone) {
3612 mDone.set(false);
3613 }
3614 }
3615
3616 public void waitForCompletion() {
3617 synchronized (mDone) {
3618 while (mDone.get() == false) {
3619 try {
3620 mDone.wait();
3621 } catch (InterruptedException e) { }
3622 }
3623 }
3624 }
3625
3626 int getResult() {
3627 return mResult;
3628 }
3629
3630 @Override
3631 public void packageInstalled(String packageName, int returnCode)
3632 throws RemoteException {
3633 synchronized (mDone) {
3634 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003635 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003636 mDone.set(true);
3637 mDone.notifyAll();
3638 }
3639 }
3640 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003641
3642 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3643 final AtomicBoolean mDone = new AtomicBoolean();
3644 int mResult;
3645
3646 public void reset() {
3647 synchronized (mDone) {
3648 mDone.set(false);
3649 }
3650 }
3651
3652 public void waitForCompletion() {
3653 synchronized (mDone) {
3654 while (mDone.get() == false) {
3655 try {
3656 mDone.wait();
3657 } catch (InterruptedException e) { }
3658 }
3659 }
3660 }
3661
3662 @Override
3663 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3664 synchronized (mDone) {
3665 mResult = returnCode;
3666 mDone.set(true);
3667 mDone.notifyAll();
3668 }
3669 }
3670 }
3671
Christopher Tate75a99702011-05-18 16:28:19 -07003672 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003673 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003674
3675 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3676 boolean okay = true;
3677
3678 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3679
3680 // The file content is an .apk file. Copy it out to a staging location and
3681 // attempt to install it.
3682 File apkFile = new File(mDataDir, info.packageName);
3683 try {
3684 FileOutputStream apkStream = new FileOutputStream(apkFile);
3685 byte[] buffer = new byte[32 * 1024];
3686 long size = info.size;
3687 while (size > 0) {
3688 long toRead = (buffer.length < size) ? buffer.length : size;
3689 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003690 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003691 apkStream.write(buffer, 0, didRead);
3692 size -= didRead;
3693 }
3694 apkStream.close();
3695
3696 // make sure the installer can read it
3697 apkFile.setReadable(true, false);
3698
3699 // Now install it
3700 Uri packageUri = Uri.fromFile(apkFile);
3701 mInstallObserver.reset();
3702 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003703 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3704 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003705 mInstallObserver.waitForCompletion();
3706
3707 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3708 // The only time we continue to accept install of data even if the
3709 // apk install failed is if we had already determined that we could
3710 // accept the data regardless.
3711 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3712 okay = false;
3713 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003714 } else {
3715 // Okay, the install succeeded. Make sure it was the right app.
3716 boolean uninstall = false;
3717 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3718 Slog.w(TAG, "Restore stream claimed to include apk for "
3719 + info.packageName + " but apk was really "
3720 + mInstallObserver.mPackageName);
3721 // delete the package we just put in place; it might be fraudulent
3722 okay = false;
3723 uninstall = true;
3724 } else {
3725 try {
3726 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3727 PackageManager.GET_SIGNATURES);
3728 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3729 Slog.w(TAG, "Restore stream contains apk of package "
3730 + info.packageName + " but it disallows backup/restore");
3731 okay = false;
3732 } else {
3733 // So far so good -- do the signatures match the manifest?
3734 Signature[] sigs = mManifestSignatures.get(info.packageName);
Christopher Tate2baf6dc2013-05-06 13:07:05 -07003735 if (signaturesMatch(sigs, pkg)) {
3736 // If this is a system-uid app without a declared backup agent,
3737 // don't restore any of the file data.
3738 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
3739 && (pkg.applicationInfo.backupAgentName == null)) {
3740 Slog.w(TAG, "Installed app " + info.packageName
3741 + " has restricted uid and no agent");
3742 okay = false;
3743 }
3744 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003745 Slog.w(TAG, "Installed app " + info.packageName
3746 + " signatures do not match restore manifest");
3747 okay = false;
3748 uninstall = true;
3749 }
3750 }
3751 } catch (NameNotFoundException e) {
3752 Slog.w(TAG, "Install of package " + info.packageName
3753 + " succeeded but now not found");
3754 okay = false;
3755 }
3756 }
3757
3758 // If we're not okay at this point, we need to delete the package
3759 // that we just installed.
3760 if (uninstall) {
3761 mDeleteObserver.reset();
3762 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3763 mDeleteObserver, 0);
3764 mDeleteObserver.waitForCompletion();
3765 }
Christopher Tate75a99702011-05-18 16:28:19 -07003766 }
3767 } catch (IOException e) {
3768 Slog.e(TAG, "Unable to transcribe restored apk for install");
3769 okay = false;
3770 } finally {
3771 apkFile.delete();
3772 }
3773
3774 return okay;
3775 }
3776
3777 // Given an actual file content size, consume the post-content padding mandated
3778 // by the tar format.
3779 void skipTarPadding(long size, InputStream instream) throws IOException {
3780 long partial = (size + 512) % 512;
3781 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003782 final int needed = 512 - (int)partial;
3783 byte[] buffer = new byte[needed];
3784 if (readExactly(instream, buffer, 0, needed) == needed) {
3785 mBytes += needed;
3786 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003787 }
3788 }
3789
3790 // Returns a policy constant; takes a buffer arg to reduce memory churn
3791 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3792 throws IOException {
3793 // Fail on suspiciously large manifest files
3794 if (info.size > 64 * 1024) {
3795 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3796 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003797
Christopher Tate75a99702011-05-18 16:28:19 -07003798 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003799 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3800 mBytes += info.size;
3801 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003802
3803 RestorePolicy policy = RestorePolicy.IGNORE;
3804 String[] str = new String[1];
3805 int offset = 0;
3806
3807 try {
3808 offset = extractLine(buffer, offset, str);
3809 int version = Integer.parseInt(str[0]);
3810 if (version == BACKUP_MANIFEST_VERSION) {
3811 offset = extractLine(buffer, offset, str);
3812 String manifestPackage = str[0];
3813 // TODO: handle <original-package>
3814 if (manifestPackage.equals(info.packageName)) {
3815 offset = extractLine(buffer, offset, str);
3816 version = Integer.parseInt(str[0]); // app version
3817 offset = extractLine(buffer, offset, str);
3818 int platformVersion = Integer.parseInt(str[0]);
3819 offset = extractLine(buffer, offset, str);
3820 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3821 offset = extractLine(buffer, offset, str);
3822 boolean hasApk = str[0].equals("1");
3823 offset = extractLine(buffer, offset, str);
3824 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003825 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003826 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003827 for (int i = 0; i < numSigs; i++) {
3828 offset = extractLine(buffer, offset, str);
3829 sigs[i] = new Signature(str[0]);
3830 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003831 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003832
3833 // Okay, got the manifest info we need...
3834 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003835 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3836 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003837 // Fall through to IGNORE if the app explicitly disallows backup
3838 final int flags = pkgInfo.applicationInfo.flags;
3839 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003840 // Restore system-uid-space packages only if they have
3841 // defined a custom backup agent
3842 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3843 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3844 // Verify signatures against any installed version; if they
3845 // don't match, then we fall though and ignore the data. The
3846 // signatureMatch() method explicitly ignores the signature
3847 // check for packages installed on the system partition, because
3848 // such packages are signed with the platform cert instead of
3849 // the app developer's cert, so they're different on every
3850 // device.
3851 if (signaturesMatch(sigs, pkgInfo)) {
3852 if (pkgInfo.versionCode >= version) {
3853 Slog.i(TAG, "Sig + version match; taking data");
3854 policy = RestorePolicy.ACCEPT;
3855 } else {
3856 // The data is from a newer version of the app than
3857 // is presently installed. That means we can only
3858 // use it if the matching apk is also supplied.
3859 Slog.d(TAG, "Data version " + version
3860 + " is newer than installed version "
3861 + pkgInfo.versionCode + " - requiring apk");
3862 policy = RestorePolicy.ACCEPT_IF_APK;
3863 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003864 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003865 Slog.w(TAG, "Restore manifest signatures do not match "
3866 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003867 }
Christopher Tate75a99702011-05-18 16:28:19 -07003868 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003869 Slog.w(TAG, "Package " + info.packageName
3870 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003871 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003872 } else {
3873 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3874 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003875 }
3876 } catch (NameNotFoundException e) {
3877 // Okay, the target app isn't installed. We can process
3878 // the restore properly only if the dataset provides the
3879 // apk file and we can successfully install it.
3880 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3881 + " not installed; requiring apk in dataset");
3882 policy = RestorePolicy.ACCEPT_IF_APK;
3883 }
3884
3885 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3886 Slog.i(TAG, "Cannot restore package " + info.packageName
3887 + " without the matching .apk");
3888 }
3889 } else {
3890 Slog.i(TAG, "Missing signature on backed-up package "
3891 + info.packageName);
3892 }
3893 } else {
3894 Slog.i(TAG, "Expected package " + info.packageName
3895 + " but restore manifest claims " + manifestPackage);
3896 }
3897 } else {
3898 Slog.i(TAG, "Unknown restore manifest version " + version
3899 + " for package " + info.packageName);
3900 }
3901 } catch (NumberFormatException e) {
3902 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003903 } catch (IllegalArgumentException e) {
3904 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003905 }
3906
3907 return policy;
3908 }
3909
3910 // Builds a line from a byte buffer starting at 'offset', and returns
3911 // the index of the next unconsumed data in the buffer.
3912 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3913 final int end = buffer.length;
3914 if (offset >= end) throw new IOException("Incomplete data");
3915
3916 int pos;
3917 for (pos = offset; pos < end; pos++) {
3918 byte c = buffer[pos];
3919 // at LF we declare end of line, and return the next char as the
3920 // starting point for the next time through
3921 if (c == '\n') {
3922 break;
3923 }
3924 }
3925 outStr[0] = new String(buffer, offset, pos - offset);
3926 pos++; // may be pointing an extra byte past the end but that's okay
3927 return pos;
3928 }
3929
3930 void dumpFileMetadata(FileMetadata info) {
3931 if (DEBUG) {
3932 StringBuilder b = new StringBuilder(128);
3933
3934 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003935 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003936 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3937 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3938 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3939 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3940 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3941 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3942 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3943 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3944 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3945 b.append(String.format(" %9d ", info.size));
3946
3947 Date stamp = new Date(info.mtime);
Elliott Hughes64a277d82013-03-18 17:47:22 -07003948 b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
Christopher Tate75a99702011-05-18 16:28:19 -07003949
3950 b.append(info.packageName);
3951 b.append(" :: ");
3952 b.append(info.domain);
3953 b.append(" :: ");
3954 b.append(info.path);
3955
3956 Slog.i(TAG, b.toString());
3957 }
3958 }
3959 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3960 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3961 byte[] block = new byte[512];
3962 FileMetadata info = null;
3963
3964 boolean gotHeader = readTarHeader(instream, block);
3965 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003966 try {
3967 // okay, presume we're okay, and extract the various metadata
3968 info = new FileMetadata();
3969 info.size = extractRadix(block, 124, 12, 8);
3970 info.mtime = extractRadix(block, 136, 12, 8);
3971 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003972
Christopher Tate2efd2db2011-07-19 16:32:49 -07003973 info.path = extractString(block, 345, 155); // prefix
3974 String path = extractString(block, 0, 100);
3975 if (path.length() > 0) {
3976 if (info.path.length() > 0) info.path += '/';
3977 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003978 }
Christopher Tate75a99702011-05-18 16:28:19 -07003979
Christopher Tate2efd2db2011-07-19 16:32:49 -07003980 // tar link indicator field: 1 byte at offset 156 in the header.
3981 int typeChar = block[156];
3982 if (typeChar == 'x') {
3983 // pax extended header, so we need to read that
3984 gotHeader = readPaxExtendedHeader(instream, info);
3985 if (gotHeader) {
3986 // and after a pax extended header comes another real header -- read
3987 // that to find the real file type
3988 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003989 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003990 if (!gotHeader) throw new IOException("Bad or missing pax header");
3991
3992 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003993 }
Christopher Tate75a99702011-05-18 16:28:19 -07003994
Christopher Tate2efd2db2011-07-19 16:32:49 -07003995 switch (typeChar) {
3996 case '0': info.type = BackupAgent.TYPE_FILE; break;
3997 case '5': {
3998 info.type = BackupAgent.TYPE_DIRECTORY;
3999 if (info.size != 0) {
4000 Slog.w(TAG, "Directory entry with nonzero size in header");
4001 info.size = 0;
4002 }
4003 break;
Christopher Tate75a99702011-05-18 16:28:19 -07004004 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004005 case 0: {
4006 // presume EOF
4007 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
4008 return null;
4009 }
4010 default: {
4011 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
4012 throw new IOException("Unknown entity type " + typeChar);
4013 }
Christopher Tate75a99702011-05-18 16:28:19 -07004014 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004015
4016 // Parse out the path
4017 //
4018 // first: apps/shared/unrecognized
4019 if (FullBackup.SHARED_PREFIX.regionMatches(0,
4020 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4021 // File in shared storage. !!! TODO: implement this.
4022 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08004023 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004024 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4025 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4026 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4027 info.path, 0, FullBackup.APPS_PREFIX.length())) {
4028 // App content! Parse out the package name and domain
4029
4030 // strip the apps/ prefix
4031 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4032
4033 // extract the package name
4034 int slash = info.path.indexOf('/');
4035 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4036 info.packageName = info.path.substring(0, slash);
4037 info.path = info.path.substring(slash+1);
4038
4039 // if it's a manifest we're done, otherwise parse out the domains
4040 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4041 slash = info.path.indexOf('/');
4042 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4043 info.domain = info.path.substring(0, slash);
Christopher Tate2efd2db2011-07-19 16:32:49 -07004044 info.path = info.path.substring(slash + 1);
4045 }
4046 }
4047 } catch (IOException e) {
4048 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07004049 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07004050 HEXLOG(block);
4051 }
4052 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07004053 }
4054 }
4055 return info;
4056 }
4057
Christopher Tate2efd2db2011-07-19 16:32:49 -07004058 private void HEXLOG(byte[] block) {
4059 int offset = 0;
4060 int todo = block.length;
4061 StringBuilder buf = new StringBuilder(64);
4062 while (todo > 0) {
4063 buf.append(String.format("%04x ", offset));
4064 int numThisLine = (todo > 16) ? 16 : todo;
4065 for (int i = 0; i < numThisLine; i++) {
4066 buf.append(String.format("%02x ", block[offset+i]));
4067 }
4068 Slog.i("hexdump", buf.toString());
4069 buf.setLength(0);
4070 todo -= numThisLine;
4071 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07004072 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004073 }
4074
Christopher Tate6853fcf2011-08-10 17:52:21 -07004075 // Read exactly the given number of bytes into a buffer at the stated offset.
4076 // Returns false if EOF is encountered before the requested number of bytes
4077 // could be read.
4078 int readExactly(InputStream in, byte[] buffer, int offset, int size)
4079 throws IOException {
4080 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4081
4082 int soFar = 0;
4083 while (soFar < size) {
4084 int nRead = in.read(buffer, offset + soFar, size - soFar);
4085 if (nRead <= 0) {
4086 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4087 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004088 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004089 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004090 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004091 return soFar;
4092 }
4093
4094 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4095 final int got = readExactly(instream, block, 0, 512);
4096 if (got == 0) return false; // Clean EOF
4097 if (got < 512) throw new IOException("Unable to read full block header");
4098 mBytes += 512;
4099 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07004100 }
4101
4102 // overwrites 'info' fields based on the pax extended header
4103 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4104 throws IOException {
4105 // We should never see a pax extended header larger than this
4106 if (info.size > 32*1024) {
4107 Slog.w(TAG, "Suspiciously large pax header size " + info.size
4108 + " - aborting");
4109 throw new IOException("Sanity failure: pax header size " + info.size);
4110 }
4111
4112 // read whole blocks, not just the content size
4113 int numBlocks = (int)((info.size + 511) >> 9);
4114 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07004115 if (readExactly(instream, data, 0, data.length) < data.length) {
4116 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07004117 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004118 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07004119
4120 final int contentSize = (int) info.size;
4121 int offset = 0;
4122 do {
4123 // extract the line at 'offset'
4124 int eol = offset+1;
4125 while (eol < contentSize && data[eol] != ' ') eol++;
4126 if (eol >= contentSize) {
4127 // error: we just hit EOD looking for the end of the size field
4128 throw new IOException("Invalid pax data");
4129 }
4130 // eol points to the space between the count and the key
4131 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4132 int key = eol + 1; // start of key=value
4133 eol = offset + linelen - 1; // trailing LF
4134 int value;
4135 for (value = key+1; data[value] != '=' && value <= eol; value++);
4136 if (value > eol) {
4137 throw new IOException("Invalid pax declaration");
4138 }
4139
4140 // pax requires that key/value strings be in UTF-8
4141 String keyStr = new String(data, key, value-key, "UTF-8");
4142 // -1 to strip the trailing LF
4143 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4144
4145 if ("path".equals(keyStr)) {
4146 info.path = valStr;
4147 } else if ("size".equals(keyStr)) {
4148 info.size = Long.parseLong(valStr);
4149 } else {
4150 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4151 }
4152
4153 offset += linelen;
4154 } while (offset < contentSize);
4155
4156 return true;
4157 }
4158
4159 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4160 throws IOException {
4161 long value = 0;
4162 final int end = offset + maxChars;
4163 for (int i = offset; i < end; i++) {
4164 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004165 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004166 if (b == 0 || b == ' ') break;
4167 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004168 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004169 }
4170 value = radix * value + (b - '0');
4171 }
4172 return value;
4173 }
4174
4175 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4176 final int end = offset + maxChars;
4177 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004178 // tar string fields terminate early with a NUL
4179 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004180 return new String(data, offset, eos-offset, "US-ASCII");
4181 }
4182
4183 void sendStartRestore() {
4184 if (mObserver != null) {
4185 try {
4186 mObserver.onStartRestore();
4187 } catch (RemoteException e) {
4188 Slog.w(TAG, "full restore observer went away: startRestore");
4189 mObserver = null;
4190 }
4191 }
4192 }
4193
4194 void sendOnRestorePackage(String name) {
4195 if (mObserver != null) {
4196 try {
4197 // TODO: use a more user-friendly name string
4198 mObserver.onRestorePackage(name);
4199 } catch (RemoteException e) {
4200 Slog.w(TAG, "full restore observer went away: restorePackage");
4201 mObserver = null;
4202 }
4203 }
4204 }
4205
4206 void sendEndRestore() {
4207 if (mObserver != null) {
4208 try {
4209 mObserver.onEndRestore();
4210 } catch (RemoteException e) {
4211 Slog.w(TAG, "full restore observer went away: endRestore");
4212 mObserver = null;
4213 }
4214 }
4215 }
4216 }
4217
Christopher Tatedf01dea2009-06-09 20:45:02 -07004218 // ----- Restore handling -----
4219
Christopher Tate78dd4a72009-11-04 11:49:08 -08004220 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4221 // If the target resides on the system partition, we allow it to restore
4222 // data from the like-named package in a restore set even if the signatures
4223 // do not match. (Unlike general applications, those flashed to the system
4224 // partition will be signed with the device's platform certificate, so on
4225 // different phones the same system app will have different signatures.)
4226 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004227 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004228 return true;
4229 }
4230
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004231 // Allow unsigned apps, but not signed on one device and unsigned on the other
4232 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004233 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004234 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004235 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004236 if ((storedSigs == null || storedSigs.length == 0)
4237 && (deviceSigs == null || deviceSigs.length == 0)) {
4238 return true;
4239 }
4240 if (storedSigs == null || deviceSigs == null) {
4241 return false;
4242 }
4243
Christopher Tateabce4e82009-06-18 18:35:32 -07004244 // !!! TODO: this demands that every stored signature match one
4245 // that is present on device, and does not demand the converse.
4246 // Is this this right policy?
4247 int nStored = storedSigs.length;
4248 int nDevice = deviceSigs.length;
4249
4250 for (int i=0; i < nStored; i++) {
4251 boolean match = false;
4252 for (int j=0; j < nDevice; j++) {
4253 if (storedSigs[i].equals(deviceSigs[j])) {
4254 match = true;
4255 break;
4256 }
4257 }
4258 if (!match) {
4259 return false;
4260 }
4261 }
4262 return true;
4263 }
4264
Christopher Tate2982d062011-09-06 20:35:24 -07004265 enum RestoreState {
4266 INITIAL,
4267 DOWNLOAD_DATA,
4268 PM_METADATA,
4269 RUNNING_QUEUE,
4270 FINAL
4271 }
4272
4273 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004274 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004275 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004276 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004277 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004278 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004279 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004280 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004281 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004282 private long mStartRealtime;
4283 private PackageManagerBackupAgent mPmAgent;
4284 private List<PackageInfo> mAgentPackages;
4285 private ArrayList<PackageInfo> mRestorePackages;
4286 private RestoreState mCurrentState;
4287 private int mCount;
4288 private boolean mFinished;
4289 private int mStatus;
4290 private File mBackupDataName;
4291 private File mNewStateName;
4292 private File mSavedStateName;
4293 private ParcelFileDescriptor mBackupData;
4294 private ParcelFileDescriptor mNewState;
4295 private PackageInfo mCurrentPackage;
4296
Christopher Tatedf01dea2009-06-09 20:45:02 -07004297
Christopher Tate5cbbf562009-06-22 16:44:51 -07004298 class RestoreRequest {
4299 public PackageInfo app;
4300 public int storedAppVersion;
4301
4302 RestoreRequest(PackageInfo _app, int _version) {
4303 app = _app;
4304 storedAppVersion = _version;
4305 }
4306 }
4307
Christopher Tate44a27902010-01-27 17:15:49 -08004308 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004309 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004310 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004311 mCurrentState = RestoreState.INITIAL;
4312 mFinished = false;
4313 mPmAgent = null;
4314
Christopher Tatedf01dea2009-06-09 20:45:02 -07004315 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004316 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004317 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004318 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004319 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004320 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004321
Christopher Tate284f1bb2011-07-07 14:31:18 -07004322 if (filterSet != null) {
4323 mFilterSet = new HashSet<String>();
4324 for (String pkg : filterSet) {
4325 mFilterSet.add(pkg);
4326 }
4327 } else {
4328 mFilterSet = null;
4329 }
4330
Christopher Tate5cb400b2009-06-25 16:03:14 -07004331 try {
4332 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4333 } catch (RemoteException e) {
4334 // can't happen; the transport is local
4335 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004336 }
4337
Christopher Tate2982d062011-09-06 20:35:24 -07004338 // Execute one tick of whatever state machine the task implements
4339 @Override
4340 public void execute() {
4341 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4342 switch (mCurrentState) {
4343 case INITIAL:
4344 beginRestore();
4345 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004346
Christopher Tate2982d062011-09-06 20:35:24 -07004347 case DOWNLOAD_DATA:
4348 downloadRestoreData();
4349 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004350
Christopher Tate2982d062011-09-06 20:35:24 -07004351 case PM_METADATA:
4352 restorePmMetadata();
4353 break;
4354
4355 case RUNNING_QUEUE:
4356 restoreNextAgent();
4357 break;
4358
4359 case FINAL:
4360 if (!mFinished) finalizeRestore();
4361 else {
4362 Slog.e(TAG, "Duplicate finish");
4363 }
4364 mFinished = true;
4365 break;
4366 }
4367 }
4368
4369 // Initialize and set up for the PM metadata restore, which comes first
4370 void beginRestore() {
4371 // Don't account time doing the restore as inactivity of the app
4372 // that has opened a restore session.
4373 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4374
4375 // Assume error until we successfully init everything
4376 mStatus = BackupConstants.TRANSPORT_ERROR;
4377
Christopher Tatedf01dea2009-06-09 20:45:02 -07004378 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004379 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004380 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004381
Dan Egnorefe52642009-06-24 00:16:33 -07004382 // Get the list of all packages which have backup enabled.
4383 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004384 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004385 PackageInfo omPackage = new PackageInfo();
4386 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004387 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004388
Christopher Tate2982d062011-09-06 20:35:24 -07004389 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004390 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004391 // if there's a filter set, strip out anything that isn't
4392 // present before proceeding
4393 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004394 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4395 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004396 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004397 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004398 }
4399 }
Christopher Tate2982d062011-09-06 20:35:24 -07004400 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004401 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004402 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004403 Slog.i(TAG, " " + p);
4404 }
4405 }
4406 }
Christopher Tate2982d062011-09-06 20:35:24 -07004407 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004408 } else {
4409 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004410 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004411 }
Dan Egnorefe52642009-06-24 00:16:33 -07004412
Christopher Tate7d562ec2009-06-25 18:03:43 -07004413 // let the observer know that we're running
4414 if (mObserver != null) {
4415 try {
4416 // !!! TODO: get an actual count from the transport after
4417 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004418 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004419 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004420 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004421 mObserver = null;
4422 }
4423 }
Christopher Tate2982d062011-09-06 20:35:24 -07004424 } catch (RemoteException e) {
4425 // Something has gone catastrophically wrong with the transport
4426 Slog.e(TAG, "Error communicating with transport for restore");
4427 executeNextState(RestoreState.FINAL);
4428 return;
4429 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004430
Christopher Tate2982d062011-09-06 20:35:24 -07004431 mStatus = BackupConstants.TRANSPORT_OK;
4432 executeNextState(RestoreState.DOWNLOAD_DATA);
4433 }
4434
4435 void downloadRestoreData() {
4436 // Note that the download phase can be very time consuming, but we're executing
4437 // it inline here on the looper. This is "okay" because it is not calling out to
4438 // third party code; the transport is "trusted," and so we assume it is being a
4439 // good citizen and timing out etc when appropriate.
4440 //
4441 // TODO: when appropriate, move the download off the looper and rearrange the
4442 // error handling around that.
4443 try {
4444 mStatus = mTransport.startRestore(mToken,
4445 mRestorePackages.toArray(new PackageInfo[0]));
4446 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004447 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004448 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004449 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004450 return;
4451 }
Christopher Tate2982d062011-09-06 20:35:24 -07004452 } catch (RemoteException e) {
4453 Slog.e(TAG, "Error communicating with transport for restore");
4454 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4455 mStatus = BackupConstants.TRANSPORT_ERROR;
4456 executeNextState(RestoreState.FINAL);
4457 return;
4458 }
Dan Egnorefe52642009-06-24 00:16:33 -07004459
Christopher Tate2982d062011-09-06 20:35:24 -07004460 // Successful download of the data to be parceled out to the apps, so off we go.
4461 executeNextState(RestoreState.PM_METADATA);
4462 }
4463
4464 void restorePmMetadata() {
4465 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004466 String packageName = mTransport.nextRestorePackage();
4467 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004468 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004469 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004470 mStatus = BackupConstants.TRANSPORT_ERROR;
4471 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004472 return;
4473 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004474 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004475 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004476 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004477 mStatus = BackupConstants.TRANSPORT_OK;
4478 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004479 return;
4480 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004481 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004482 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004483 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004484 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004485 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004486 return;
4487 }
4488
4489 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004490 PackageInfo omPackage = new PackageInfo();
4491 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4492 mPmAgent = new PackageManagerBackupAgent(
4493 mPackageManager, mAgentPackages);
4494 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004495 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004496 // The PM agent called operationComplete() already, because our invocation
4497 // of it is process-local and therefore synchronous. That means that a
4498 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4499 // proceed with running the queue do we remove that pending message and
4500 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004501
Christopher Tate8c032472009-07-02 14:28:47 -07004502 // Verify that the backup set includes metadata. If not, we can't do
4503 // signature/version verification etc, so we simply do not proceed with
4504 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004505 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004506 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004507 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004508 "Package manager restore metadata missing");
4509 mStatus = BackupConstants.TRANSPORT_ERROR;
4510 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4511 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004512 return;
4513 }
Christopher Tate2982d062011-09-06 20:35:24 -07004514 } catch (RemoteException e) {
4515 Slog.e(TAG, "Error communicating with transport for restore");
4516 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4517 mStatus = BackupConstants.TRANSPORT_ERROR;
4518 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4519 executeNextState(RestoreState.FINAL);
4520 return;
4521 }
Christopher Tate8c032472009-07-02 14:28:47 -07004522
Christopher Tate2982d062011-09-06 20:35:24 -07004523 // Metadata is intact, so we can now run the restore queue. If we get here,
4524 // we have already enqueued the necessary next-step message on the looper.
4525 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004526
Christopher Tate2982d062011-09-06 20:35:24 -07004527 void restoreNextAgent() {
4528 try {
4529 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004530
Christopher Tate2982d062011-09-06 20:35:24 -07004531 if (packageName == null) {
4532 Slog.e(TAG, "Error getting next restore package");
4533 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4534 executeNextState(RestoreState.FINAL);
4535 return;
4536 } else if (packageName.equals("")) {
4537 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4538 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4539 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4540 executeNextState(RestoreState.FINAL);
4541 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004542 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004543
4544 if (mObserver != null) {
4545 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004546 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004547 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004548 Slog.d(TAG, "Restore observer died in onUpdate");
4549 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004550 }
4551 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004552
Christopher Tate2982d062011-09-06 20:35:24 -07004553 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4554 if (metaInfo == null) {
4555 Slog.e(TAG, "Missing metadata for " + packageName);
4556 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4557 "Package metadata missing");
4558 executeNextState(RestoreState.RUNNING_QUEUE);
4559 return;
Christopher Tate84725812010-02-04 15:52:40 -08004560 }
4561
Christopher Tate2982d062011-09-06 20:35:24 -07004562 PackageInfo packageInfo;
4563 try {
4564 int flags = PackageManager.GET_SIGNATURES;
4565 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4566 } catch (NameNotFoundException e) {
4567 Slog.e(TAG, "Invalid package restoring data", e);
4568 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4569 "Package missing on device");
4570 executeNextState(RestoreState.RUNNING_QUEUE);
4571 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004572 }
4573
Christopher Tatee7287a02012-09-07 18:32:12 -07004574 if (packageInfo.applicationInfo.backupAgentName == null
4575 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4576 if (DEBUG) {
4577 Slog.i(TAG, "Data exists for package " + packageName
4578 + " but app has no agent; skipping");
4579 }
4580 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4581 "Package has no agent");
4582 executeNextState(RestoreState.RUNNING_QUEUE);
4583 return;
4584 }
4585
Christopher Tate2982d062011-09-06 20:35:24 -07004586 if (metaInfo.versionCode > packageInfo.versionCode) {
4587 // Data is from a "newer" version of the app than we have currently
4588 // installed. If the app has not declared that it is prepared to
4589 // handle this case, we do not attempt the restore.
4590 if ((packageInfo.applicationInfo.flags
4591 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4592 String message = "Version " + metaInfo.versionCode
4593 + " > installed version " + packageInfo.versionCode;
4594 Slog.w(TAG, "Package " + packageName + ": " + message);
4595 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4596 packageName, message);
4597 executeNextState(RestoreState.RUNNING_QUEUE);
4598 return;
4599 } else {
4600 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4601 + " > installed " + packageInfo.versionCode
4602 + " but restoreAnyVersion");
4603 }
4604 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004605
Christopher Tate2982d062011-09-06 20:35:24 -07004606 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4607 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4608 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4609 "Signature mismatch");
4610 executeNextState(RestoreState.RUNNING_QUEUE);
4611 return;
4612 }
4613
4614 if (DEBUG) Slog.v(TAG, "Package " + packageName
4615 + " restore version [" + metaInfo.versionCode
4616 + "] is compatible with installed version ["
4617 + packageInfo.versionCode + "]");
4618
4619 // Then set up and bind the agent
4620 IBackupAgent agent = bindToAgentSynchronous(
4621 packageInfo.applicationInfo,
4622 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4623 if (agent == null) {
4624 Slog.w(TAG, "Can't find backup agent for " + packageName);
4625 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4626 "Restore agent missing");
4627 executeNextState(RestoreState.RUNNING_QUEUE);
4628 return;
4629 }
4630
4631 // And then finally start the restore on this agent
4632 try {
4633 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4634 ++mCount;
4635 } catch (Exception e) {
4636 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4637 agentErrorCleanup();
4638 executeNextState(RestoreState.RUNNING_QUEUE);
4639 }
4640 } catch (RemoteException e) {
4641 Slog.e(TAG, "Unable to fetch restore data from transport");
4642 mStatus = BackupConstants.TRANSPORT_ERROR;
4643 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004644 }
4645 }
4646
Christopher Tate2982d062011-09-06 20:35:24 -07004647 void finalizeRestore() {
4648 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4649
4650 try {
4651 mTransport.finishRestore();
4652 } catch (RemoteException e) {
4653 Slog.e(TAG, "Error finishing restore", e);
4654 }
4655
4656 if (mObserver != null) {
4657 try {
4658 mObserver.restoreFinished(mStatus);
4659 } catch (RemoteException e) {
4660 Slog.d(TAG, "Restore observer died at restoreFinished");
4661 }
4662 }
4663
4664 // If this was a restoreAll operation, record that this was our
4665 // ancestral dataset, as well as the set of apps that are possibly
4666 // restoreable from the dataset
4667 if (mTargetPackage == null && mPmAgent != null) {
4668 mAncestralPackages = mPmAgent.getRestoredPackages();
4669 mAncestralToken = mToken;
4670 writeRestoreTokens();
4671 }
4672
4673 // We must under all circumstances tell the Package Manager to
4674 // proceed with install notifications if it's waiting for us.
4675 if (mPmToken > 0) {
4676 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4677 try {
4678 mPackageManagerBinder.finishPackageInstall(mPmToken);
4679 } catch (RemoteException e) { /* can't happen */ }
4680 }
4681
4682 // Furthermore we need to reset the session timeout clock
4683 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4684 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4685 TIMEOUT_RESTORE_INTERVAL);
4686
4687 // done; we can finally release the wakelock
4688 Slog.i(TAG, "Restore complete.");
4689 mWakelock.release();
4690 }
4691
4692 // Call asynchronously into the app, passing it the restore data. The next step
4693 // after this is always a callback, either operationComplete() or handleTimeout().
4694 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004695 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004696 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004697 final String packageName = app.packageName;
4698
Christopher Tate2982d062011-09-06 20:35:24 -07004699 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004700
Christopher Tatec7b31e32009-06-10 15:49:30 -07004701 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004702 mBackupDataName = new File(mDataDir, packageName + ".restore");
4703 mNewStateName = new File(mStateDir, packageName + ".new");
4704 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004705
Christopher Tate4a627c72011-04-01 14:43:32 -07004706 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004707 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004708 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004709 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004710 ParcelFileDescriptor.MODE_READ_WRITE |
4711 ParcelFileDescriptor.MODE_CREATE |
4712 ParcelFileDescriptor.MODE_TRUNCATE);
4713
rpcraigebab0ae2012-12-04 09:37:23 -05004714 if (!SELinux.restorecon(mBackupDataName)) {
4715 Slog.e(TAG, "SElinux restorecon failed for " + mBackupDataName);
4716 }
4717
Christopher Tate2982d062011-09-06 20:35:24 -07004718 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004719 // Transport-level failure, so we wind everything up and
4720 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004721 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004722 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004723 mBackupData.close();
4724 mBackupDataName.delete();
4725 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004726 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004727 }
4728
4729 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004730 mBackupData.close();
4731 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004732 ParcelFileDescriptor.MODE_READ_ONLY);
4733
Christopher Tate2982d062011-09-06 20:35:24 -07004734 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004735 ParcelFileDescriptor.MODE_READ_WRITE |
4736 ParcelFileDescriptor.MODE_CREATE |
4737 ParcelFileDescriptor.MODE_TRUNCATE);
4738
Christopher Tate44a27902010-01-27 17:15:49 -08004739 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004740 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4741 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004742 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004743 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004744 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004745 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004746
Christopher Tate2982d062011-09-06 20:35:24 -07004747 // After a restore failure we go back to running the queue. If there
4748 // are no more packages to be restored that will be handled by the
4749 // next step.
4750 executeNextState(RestoreState.RUNNING_QUEUE);
4751 }
4752 }
Chris Tate249345b2010-10-29 12:57:04 -07004753
Christopher Tate2982d062011-09-06 20:35:24 -07004754 void agentErrorCleanup() {
4755 // If the agent fails restore, it might have put the app's data
4756 // into an incoherent state. For consistency we wipe its data
4757 // again in this case before continuing with normal teardown
4758 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4759 agentCleanup();
4760 }
4761
4762 void agentCleanup() {
4763 mBackupDataName.delete();
4764 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4765 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4766 mBackupData = mNewState = null;
4767
4768 // if everything went okay, remember the recorded state now
4769 //
4770 // !!! TODO: the restored data should be migrated on the server
4771 // side into the current dataset. In that case the new state file
4772 // we just created would reflect the data already extant in the
4773 // backend, so there'd be nothing more to do. Until that happens,
4774 // however, we need to make sure that we record the data to the
4775 // current backend dataset. (Yes, this means shipping the data over
4776 // the wire in both directions. That's bad, but consistency comes
4777 // first, then efficiency.) Once we introduce server-side data
4778 // migration to the newly-restored device's dataset, we will change
4779 // the following from a discard of the newly-written state to the
4780 // "correct" operation of renaming into the canonical state blob.
4781 mNewStateName.delete(); // TODO: remove; see above comment
4782 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4783
4784 // If this wasn't the PM pseudopackage, tear down the agent side
4785 if (mCurrentPackage.applicationInfo != null) {
4786 // unbind and tidy up even on timeout or failure
4787 try {
4788 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4789
4790 // The agent was probably running with a stub Application object,
4791 // which isn't a valid run mode for the main app logic. Shut
4792 // down the app so that next time it's launched, it gets the
4793 // usual full initialization. Note that this is only done for
4794 // full-system restores: when a single app has requested a restore,
4795 // it is explicitly not killed following that operation.
4796 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4797 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4798 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4799 + mCurrentPackage.applicationInfo.processName);
4800 mActivityManager.killApplicationProcess(
4801 mCurrentPackage.applicationInfo.processName,
4802 mCurrentPackage.applicationInfo.uid);
4803 }
4804 } catch (RemoteException e) {
4805 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004806 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004807 }
Christopher Tate2982d062011-09-06 20:35:24 -07004808
4809 // The caller is responsible for reestablishing the state machine; our
4810 // responsibility here is to clear the decks for whatever comes next.
4811 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4812 synchronized (mCurrentOpLock) {
4813 mCurrentOperations.clear();
4814 }
4815 }
4816
4817 // A call to agent.doRestore() has been positively acknowledged as complete
4818 @Override
4819 public void operationComplete() {
4820 int size = (int) mBackupDataName.length();
4821 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4822 // Just go back to running the restore queue
4823 agentCleanup();
4824
4825 executeNextState(RestoreState.RUNNING_QUEUE);
4826 }
4827
4828 // A call to agent.doRestore() has timed out
4829 @Override
4830 public void handleTimeout() {
4831 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4832 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4833 mCurrentPackage.packageName, "restore timeout");
4834 // Handle like an agent that threw on invocation: wipe it and go on to the next
4835 agentErrorCleanup();
4836 executeNextState(RestoreState.RUNNING_QUEUE);
4837 }
4838
4839 void executeNextState(RestoreState nextState) {
4840 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4841 + this + " nextState=" + nextState);
4842 mCurrentState = nextState;
4843 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4844 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004845 }
4846 }
4847
Christopher Tate44a27902010-01-27 17:15:49 -08004848 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004849 IBackupTransport mTransport;
4850 PackageInfo mPackage;
4851
Christopher Tate44a27902010-01-27 17:15:49 -08004852 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004853 mTransport = transport;
4854 mPackage = packageInfo;
4855 }
4856
Christopher Tateee0e78a2009-07-02 11:17:03 -07004857 public void run() {
4858 try {
4859 // Clear the on-device backup state to ensure a full backup next time
4860 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4861 File stateFile = new File(stateDir, mPackage.packageName);
4862 stateFile.delete();
4863
4864 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004865 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004866 mTransport.clearBackupData(mPackage);
4867 } catch (RemoteException e) {
4868 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004869 } catch (Exception e) {
4870 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004871 } finally {
4872 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004873 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004874 mTransport.finishBackup();
4875 } catch (RemoteException e) {
4876 // can't happen; the transport is local
4877 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004878
4879 // Last but not least, release the cpu
4880 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004881 }
4882 }
4883 }
4884
Christopher Tate44a27902010-01-27 17:15:49 -08004885 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004886 HashSet<String> mQueue;
4887
Christopher Tate44a27902010-01-27 17:15:49 -08004888 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004889 mQueue = transportNames;
4890 }
4891
Christopher Tate4cc86e12009-09-21 19:36:51 -07004892 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004893 try {
4894 for (String transportName : mQueue) {
4895 IBackupTransport transport = getTransport(transportName);
4896 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004897 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004898 continue;
4899 }
4900
Joe Onorato8a9b2202010-02-26 18:56:32 -08004901 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004902 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004903 long startRealtime = SystemClock.elapsedRealtime();
4904 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004905
Christopher Tate4cc86e12009-09-21 19:36:51 -07004906 if (status == BackupConstants.TRANSPORT_OK) {
4907 status = transport.finishBackup();
4908 }
4909
4910 // Okay, the wipe really happened. Clean up our local bookkeeping.
4911 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004912 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004913 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004914 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004915 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004916 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004917 synchronized (mQueueLock) {
4918 recordInitPendingLocked(false, transportName);
4919 }
Dan Egnor726247c2009-09-29 19:12:31 -07004920 } else {
4921 // If this didn't work, requeue this one and try again
4922 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004923 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004924 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004925 synchronized (mQueueLock) {
4926 recordInitPendingLocked(true, transportName);
4927 }
4928 // do this via another alarm to make sure of the wakelock states
4929 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004930 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004931 + transportName + " resched in " + delay);
4932 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4933 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004934 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004935 }
4936 } catch (RemoteException e) {
4937 // can't happen; the transports are local
4938 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004939 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004940 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004941 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004942 mWakelock.release();
4943 }
4944 }
4945 }
4946
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004947 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004948 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004949 dataChangedImpl(packageName, targets);
4950 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004951
Christopher Tatea3d55342012-03-27 13:16:18 -07004952 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004953 // Record that we need a backup pass for the caller. Since multiple callers
4954 // may share a uid, we need to note all candidates within that uid and schedule
4955 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004956 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004957
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004958 if (targets == null) {
4959 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4960 + " uid=" + Binder.getCallingUid());
4961 return;
4962 }
4963
4964 synchronized (mQueueLock) {
4965 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004966 if (targets.contains(packageName)) {
4967 // Add the caller to the set of pending backups. If there is
4968 // one already there, then overwrite it, but no harm done.
4969 BackupRequest req = new BackupRequest(packageName);
4970 if (mPendingBackups.put(packageName, req) == null) {
4971 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004972
Christopher Tatea3d55342012-03-27 13:16:18 -07004973 // Journal this request in case of crash. The put()
4974 // operation returned null when this package was not already
4975 // in the set; we want to avoid touching the disk redundantly.
4976 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004977
Christopher Tatea3d55342012-03-27 13:16:18 -07004978 if (MORE_DEBUG) {
4979 int numKeys = mPendingBackups.size();
4980 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4981 for (BackupRequest b : mPendingBackups.values()) {
4982 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004983 }
4984 }
4985 }
4986 }
4987 }
4988 }
4989
4990 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004991 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004992 // If the caller does not hold the BACKUP permission, it can only request a
4993 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004994 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004995 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004996 synchronized (mBackupParticipants) {
4997 return mBackupParticipants.get(Binder.getCallingUid());
4998 }
4999 }
5000
5001 // a caller with full permission can ask to back up any participating app
5002 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07005003 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005004 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07005005 int N = mBackupParticipants.size();
5006 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005007 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07005008 if (s != null) {
5009 targets.addAll(s);
5010 }
5011 }
5012 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005013 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07005014 }
Christopher Tate46758122009-05-06 11:22:00 -07005015
Christopher Tatecde87f42009-06-12 12:55:53 -07005016 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005017 RandomAccessFile out = null;
5018 try {
5019 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5020 out = new RandomAccessFile(mJournal, "rws");
5021 out.seek(out.length());
5022 out.writeUTF(str);
5023 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005024 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005025 mJournal = null;
5026 } finally {
5027 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07005028 }
5029 }
5030
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005031 // ----- IBackupManager binder interface -----
5032
5033 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005034 final int callingUserHandle = UserHandle.getCallingUserId();
5035 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005036 // App is running under a non-owner user profile. For now, we do not back
5037 // up data from secondary user profiles.
5038 // TODO: backups for all user profiles.
5039 if (MORE_DEBUG) {
5040 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5041 + callingUserHandle);
5042 }
5043 return;
5044 }
5045
Christopher Tatea3d55342012-03-27 13:16:18 -07005046 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005047 if (targets == null) {
5048 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5049 + " uid=" + Binder.getCallingUid());
5050 return;
5051 }
5052
5053 mBackupHandler.post(new Runnable() {
5054 public void run() {
5055 dataChangedImpl(packageName, targets);
5056 }
5057 });
5058 }
5059
Christopher Tateee0e78a2009-07-02 11:17:03 -07005060 // Clear the given package's backup data from the current transport
5061 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005062 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005063 PackageInfo info;
5064 try {
5065 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5066 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005067 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07005068 return;
5069 }
5070
5071 // If the caller does not hold the BACKUP permission, it can only request a
5072 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07005073 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005074 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07005075 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5076 apps = mBackupParticipants.get(Binder.getCallingUid());
5077 } else {
5078 // a caller with full permission can ask to back up any participating app
5079 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08005080 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07005081 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07005082 int N = mBackupParticipants.size();
5083 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005084 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005085 if (s != null) {
5086 apps.addAll(s);
5087 }
5088 }
5089 }
5090
Christopher Tatea3d55342012-03-27 13:16:18 -07005091 // Is the given app an available participant?
5092 if (apps.contains(packageName)) {
5093 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5094 // found it; fire off the clear request
5095 synchronized (mQueueLock) {
5096 long oldId = Binder.clearCallingIdentity();
5097 mWakelock.acquire();
5098 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5099 new ClearParams(getTransport(mCurrentTransport), info));
5100 mBackupHandler.sendMessage(msg);
5101 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005102 }
5103 }
5104 }
5105
Christopher Tateace7f092009-06-15 18:07:25 -07005106 // Run a backup pass immediately for any applications that have declared
5107 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07005108 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04005109 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07005110
Joe Onorato8a9b2202010-02-26 18:56:32 -08005111 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07005112 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005113 // Because the alarms we are using can jitter, and we want an *immediate*
5114 // backup pass to happen, we restart the timer beginning with "next time,"
5115 // then manually fire the backup trigger intent ourselves.
5116 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07005117 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07005118 mRunBackupIntent.send();
5119 } catch (PendingIntent.CanceledException e) {
5120 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08005121 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07005122 }
Christopher Tate46758122009-05-06 11:22:00 -07005123 }
5124 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005125
Christopher Tated2c0cd42011-09-15 15:51:29 -07005126 boolean deviceIsProvisioned() {
5127 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07005128 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005129 }
5130
Christopher Tate4a627c72011-04-01 14:43:32 -07005131 // Run a *full* backup pass for the given package, writing the resulting data stream
5132 // to the supplied file descriptor. This method is synchronous and does not return
5133 // to the caller until the backup has been completed.
Christopher Tate294b5122013-02-19 14:08:59 -08005134 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5135 boolean includeObbs, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005136 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005137 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5138
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005139 final int callingUserHandle = UserHandle.getCallingUserId();
5140 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005141 throw new IllegalStateException("Backup supported only for the device owner");
5142 }
5143
Christopher Tate4a627c72011-04-01 14:43:32 -07005144 // Validate
5145 if (!doAllApps) {
5146 if (!includeShared) {
5147 // If we're backing up shared data (sdcard or equivalent), then we can run
5148 // without any supplied app names. Otherwise, we'd be doing no work, so
5149 // report the error.
5150 if (pkgList == null || pkgList.length == 0) {
5151 throw new IllegalArgumentException(
5152 "Backup requested but neither shared nor any apps named");
5153 }
5154 }
5155 }
5156
Christopher Tate4a627c72011-04-01 14:43:32 -07005157 long oldId = Binder.clearCallingIdentity();
5158 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005159 // Doesn't make sense to do a full backup prior to setup
5160 if (!deviceIsProvisioned()) {
5161 Slog.i(TAG, "Full backup not supported before setup");
5162 return;
5163 }
5164
5165 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
Christopher Tate294b5122013-02-19 14:08:59 -08005166 + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
Christopher Tated2c0cd42011-09-15 15:51:29 -07005167 + " pkgs=" + pkgList);
5168 Slog.i(TAG, "Beginning full backup...");
5169
Christopher Tate294b5122013-02-19 14:08:59 -08005170 FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5171 includeShared, doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005172 final int token = generateToken();
5173 synchronized (mFullConfirmations) {
5174 mFullConfirmations.put(token, params);
5175 }
5176
Christopher Tate75a99702011-05-18 16:28:19 -07005177 // start up the confirmation UI
5178 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5179 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5180 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005181 mFullConfirmations.delete(token);
5182 return;
5183 }
Christopher Tate75a99702011-05-18 16:28:19 -07005184
5185 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005186 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5187
5188 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005189 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005190
5191 // wait for the backup to be performed
5192 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5193 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005194 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005195 try {
5196 fd.close();
5197 } catch (IOException e) {
5198 // just eat it
5199 }
Christopher Tate75a99702011-05-18 16:28:19 -07005200 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005201 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005202 }
Christopher Tate75a99702011-05-18 16:28:19 -07005203 }
5204
5205 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005206 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005207
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005208 final int callingUserHandle = UserHandle.getCallingUserId();
5209 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005210 throw new IllegalStateException("Restore supported only for the device owner");
5211 }
5212
Christopher Tate75a99702011-05-18 16:28:19 -07005213 long oldId = Binder.clearCallingIdentity();
5214
5215 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005216 // Check whether the device has been provisioned -- we don't handle
5217 // full restores prior to completing the setup process.
5218 if (!deviceIsProvisioned()) {
5219 Slog.i(TAG, "Full restore not permitted before setup");
5220 return;
5221 }
5222
5223 Slog.i(TAG, "Beginning full restore...");
5224
Christopher Tate75a99702011-05-18 16:28:19 -07005225 FullRestoreParams params = new FullRestoreParams(fd);
5226 final int token = generateToken();
5227 synchronized (mFullConfirmations) {
5228 mFullConfirmations.put(token, params);
5229 }
5230
5231 // start up the confirmation UI
5232 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5233 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5234 Slog.e(TAG, "Unable to launch full restore confirmation");
5235 mFullConfirmations.delete(token);
5236 return;
5237 }
5238
5239 // make sure the screen is lit for the user interaction
5240 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5241
5242 // start the confirmation countdown
5243 startConfirmationTimeout(token, params);
5244
5245 // wait for the restore to be performed
5246 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5247 waitForCompletion(params);
5248 } finally {
5249 try {
5250 fd.close();
5251 } catch (IOException e) {
5252 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5253 }
5254 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005255 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005256 }
5257 }
5258
5259 boolean startConfirmationUi(int token, String action) {
5260 try {
5261 Intent confIntent = new Intent(action);
5262 confIntent.setClassName("com.android.backupconfirm",
5263 "com.android.backupconfirm.BackupRestoreConfirmation");
5264 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5265 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5266 mContext.startActivity(confIntent);
5267 } catch (ActivityNotFoundException e) {
5268 return false;
5269 }
5270 return true;
5271 }
5272
5273 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005274 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005275 + TIMEOUT_FULL_CONFIRMATION + " millis");
5276 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5277 token, 0, params);
5278 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005279 }
5280
5281 void waitForCompletion(FullParams params) {
5282 synchronized (params.latch) {
5283 while (params.latch.get() == false) {
5284 try {
5285 params.latch.wait();
5286 } catch (InterruptedException e) { /* never interrupted */ }
5287 }
5288 }
5289 }
5290
5291 void signalFullBackupRestoreCompletion(FullParams params) {
5292 synchronized (params.latch) {
5293 params.latch.set(true);
5294 params.latch.notifyAll();
5295 }
5296 }
5297
5298 // Confirm that the previously-requested full backup/restore operation can proceed. This
5299 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005300 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005301 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005302 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005303 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5304 + " allow=" + allow);
5305
5306 // TODO: possibly require not just this signature-only permission, but even
5307 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005308 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005309
5310 long oldId = Binder.clearCallingIdentity();
5311 try {
5312
5313 FullParams params;
5314 synchronized (mFullConfirmations) {
5315 params = mFullConfirmations.get(token);
5316 if (params != null) {
5317 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5318 mFullConfirmations.delete(token);
5319
5320 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005321 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005322 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005323 : MSG_RUN_FULL_RESTORE;
5324
Christopher Tate728a1c42011-07-28 18:03:03 -07005325 params.observer = observer;
5326 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005327
5328 boolean isEncrypted;
5329 try {
5330 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5331 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5332 } catch (RemoteException e) {
5333 // couldn't contact the mount service; fail "safe" and assume encryption
5334 Slog.e(TAG, "Unable to contact mount service!");
5335 isEncrypted = true;
5336 }
5337 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005338
Christopher Tate75a99702011-05-18 16:28:19 -07005339 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005340 mWakelock.acquire();
5341 Message msg = mBackupHandler.obtainMessage(verb, params);
5342 mBackupHandler.sendMessage(msg);
5343 } else {
5344 Slog.w(TAG, "User rejected full backup/restore operation");
5345 // indicate completion without having actually transferred any data
5346 signalFullBackupRestoreCompletion(params);
5347 }
5348 } else {
5349 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5350 }
5351 }
5352 } finally {
5353 Binder.restoreCallingIdentity(oldId);
5354 }
5355 }
5356
Christopher Tate8031a3d2009-07-06 16:36:05 -07005357 // Enable/disable the backup service
Christopher Tateffe0a802013-09-08 15:41:32 -07005358 @Override
Christopher Tate6ef58a12009-06-29 14:56:28 -07005359 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005360 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005361 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005362
Joe Onorato8a9b2202010-02-26 18:56:32 -08005363 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005364
Christopher Tateffe0a802013-09-08 15:41:32 -07005365 long oldId = Binder.clearCallingIdentity();
5366 try {
5367 boolean wasEnabled = mEnabled;
5368 synchronized (this) {
5369 Settings.Secure.putInt(mContext.getContentResolver(),
5370 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
5371 mEnabled = enable;
5372 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005373
Christopher Tateffe0a802013-09-08 15:41:32 -07005374 synchronized (mQueueLock) {
5375 if (enable && !wasEnabled && mProvisioned) {
5376 // if we've just been enabled, start scheduling backup passes
5377 startBackupAlarmsLocked(BACKUP_INTERVAL);
5378 } else if (!enable) {
5379 // No longer enabled, so stop running backups
5380 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005381
Christopher Tateffe0a802013-09-08 15:41:32 -07005382 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005383
Christopher Tateffe0a802013-09-08 15:41:32 -07005384 // This also constitutes an opt-out, so we wipe any data for
5385 // this device from the backend. We start that process with
5386 // an alarm in order to guarantee wakelock states.
5387 if (wasEnabled && mProvisioned) {
5388 // NOTE: we currently flush every registered transport, not just
5389 // the currently-active one.
5390 HashSet<String> allTransports;
5391 synchronized (mTransports) {
5392 allTransports = new HashSet<String>(mTransports.keySet());
5393 }
5394 // build the set of transports for which we are posting an init
5395 for (String transport : allTransports) {
5396 recordInitPendingLocked(true, transport);
5397 }
5398 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5399 mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005400 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07005401 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005402 }
Christopher Tateffe0a802013-09-08 15:41:32 -07005403 } finally {
5404 Binder.restoreCallingIdentity(oldId);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005405 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005406 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005407
Christopher Tatecce9da52010-02-03 15:11:15 -08005408 // Enable/disable automatic restore of app data at install time
5409 public void setAutoRestore(boolean doAutoRestore) {
5410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005411 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005412
Joe Onorato8a9b2202010-02-26 18:56:32 -08005413 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005414
5415 synchronized (this) {
5416 Settings.Secure.putInt(mContext.getContentResolver(),
5417 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5418 mAutoRestore = doAutoRestore;
5419 }
5420 }
5421
Christopher Tate8031a3d2009-07-06 16:36:05 -07005422 // Mark the backup service as having been provisioned
5423 public void setBackupProvisioned(boolean available) {
5424 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5425 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005426 /*
5427 * This is now a no-op; provisioning is simply the device's own setup state.
5428 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005429 }
5430
5431 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005432 // We used to use setInexactRepeating(), but that may be linked to
5433 // backups running at :00 more often than not, creating load spikes.
5434 // Schedule at an exact time for now, and also add a bit of "fuzz".
5435
5436 Random random = new Random();
5437 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5438 random.nextInt(FUZZ_MILLIS);
5439 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5440 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005441 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005442 }
5443
Christopher Tate6ef58a12009-06-29 14:56:28 -07005444 // Report whether the backup mechanism is currently enabled
5445 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005447 return mEnabled; // no need to synchronize just to read it
5448 }
5449
Christopher Tate91717492009-06-26 21:07:13 -07005450 // Report the name of the currently active transport
5451 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005452 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005453 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005454 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005455 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005456 }
5457
Christopher Tate91717492009-06-26 21:07:13 -07005458 // Report all known, available backup transports
5459 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005460 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005461
Christopher Tate91717492009-06-26 21:07:13 -07005462 String[] list = null;
5463 ArrayList<String> known = new ArrayList<String>();
5464 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5465 if (entry.getValue() != null) {
5466 known.add(entry.getKey());
5467 }
5468 }
5469
5470 if (known.size() > 0) {
5471 list = new String[known.size()];
5472 known.toArray(list);
5473 }
5474 return list;
5475 }
5476
5477 // Select which transport to use for the next backup operation. If the given
5478 // name is not one of the available transports, no action is taken and the method
5479 // returns null.
5480 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005482
5483 synchronized (mTransports) {
5484 String prevTransport = null;
5485 if (mTransports.get(transport) != null) {
5486 prevTransport = mCurrentTransport;
5487 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005488 Settings.Secure.putString(mContext.getContentResolver(),
5489 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005490 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005491 + " returning " + prevTransport);
5492 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005493 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005494 }
5495 return prevTransport;
5496 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005497 }
5498
Christopher Tatef5e1c292010-12-08 18:40:26 -08005499 // Supply the configuration Intent for the given transport. If the name is not one
5500 // of the available transports, or if the transport does not supply any configuration
5501 // UI, the method returns null.
5502 public Intent getConfigurationIntent(String transportName) {
5503 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5504 "getConfigurationIntent");
5505
5506 synchronized (mTransports) {
5507 final IBackupTransport transport = mTransports.get(transportName);
5508 if (transport != null) {
5509 try {
5510 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005511 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005512 + intent);
5513 return intent;
5514 } catch (RemoteException e) {
5515 /* fall through to return null */
5516 }
5517 }
5518 }
5519
5520 return null;
5521 }
5522
5523 // Supply the configuration summary string for the given transport. If the name is
5524 // not one of the available transports, or if the transport does not supply any
5525 // summary / destination string, the method can return null.
5526 //
5527 // This string is used VERBATIM as the summary text of the relevant Settings item!
5528 public String getDestinationString(String transportName) {
5529 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005530 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005531
5532 synchronized (mTransports) {
5533 final IBackupTransport transport = mTransports.get(transportName);
5534 if (transport != null) {
5535 try {
5536 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005537 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005538 return text;
5539 } catch (RemoteException e) {
5540 /* fall through to return null */
5541 }
5542 }
5543 }
5544
5545 return null;
5546 }
5547
Christopher Tate043dadc2009-06-02 16:11:00 -07005548 // Callback: a requested backup agent has been instantiated. This should only
5549 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005550 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005551 synchronized(mAgentConnectLock) {
5552 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005553 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005554 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5555 mConnectedAgent = agent;
5556 mConnecting = false;
5557 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005558 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005559 + " claiming agent connected");
5560 }
5561 mAgentConnectLock.notifyAll();
5562 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005563 }
5564
5565 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5566 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005567 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005568 public void agentDisconnected(String packageName) {
5569 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005570 synchronized(mAgentConnectLock) {
5571 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5572 mConnectedAgent = null;
5573 mConnecting = false;
5574 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005575 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005576 + " claiming agent disconnected");
5577 }
5578 mAgentConnectLock.notifyAll();
5579 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005580 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005581
Christopher Tate1bb69062010-02-19 17:02:12 -08005582 // An application being installed will need a restore pass, then the Package Manager
5583 // will need to be told when the restore is finished.
5584 public void restoreAtInstall(String packageName, int token) {
5585 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005586 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005587 + " attemping install-time restore");
5588 return;
5589 }
5590
5591 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005592 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005593 + " token=" + Integer.toHexString(token)
5594 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005595
Christopher Tatef0872722010-02-25 15:22:48 -08005596 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005597 // okay, we're going to attempt a restore of this package from this restore set.
5598 // The eventual message back into the Package Manager to run the post-install
5599 // steps for 'token' will be issued from the restore handling code.
5600
5601 // We can use a synthetic PackageInfo here because:
5602 // 1. We know it's valid, since the Package Manager supplied the name
5603 // 2. Only the packageName field will be used by the restore code
5604 PackageInfo pkg = new PackageInfo();
5605 pkg.packageName = packageName;
5606
5607 mWakelock.acquire();
5608 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5609 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005610 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005611 mBackupHandler.sendMessage(msg);
5612 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005613 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5614 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005615 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005616 try {
5617 mPackageManagerBinder.finishPackageInstall(token);
5618 } catch (RemoteException e) { /* can't happen */ }
5619 }
5620 }
5621
Christopher Tate8c850b72009-06-07 19:33:20 -07005622 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005623 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5624 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5625 + " transport=" + transport);
5626
5627 boolean needPermission = true;
5628 if (transport == null) {
5629 transport = mCurrentTransport;
5630
5631 if (packageName != null) {
5632 PackageInfo app = null;
5633 try {
5634 app = mPackageManager.getPackageInfo(packageName, 0);
5635 } catch (NameNotFoundException nnf) {
5636 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5637 throw new IllegalArgumentException("Package " + packageName + " not found");
5638 }
5639
5640 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5641 // So: using the current active transport, and the caller has asked
5642 // that its own package will be restored. In this narrow use case
5643 // we do not require the caller to hold the permission.
5644 needPermission = false;
5645 }
5646 }
5647 }
5648
5649 if (needPermission) {
5650 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5651 "beginRestoreSession");
5652 } else {
5653 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5654 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005655
5656 synchronized(this) {
5657 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005658 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005659 return null;
5660 }
Chris Tate44ab8452010-11-16 15:10:49 -08005661 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005662 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005663 }
5664 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005665 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005666
Christopher Tate73a3cb32010-12-13 18:27:26 -08005667 void clearRestoreSession(ActiveRestoreSession currentSession) {
5668 synchronized(this) {
5669 if (currentSession != mActiveRestoreSession) {
5670 Slog.e(TAG, "ending non-current restore session");
5671 } else {
5672 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5673 mActiveRestoreSession = null;
5674 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5675 }
5676 }
5677 }
5678
Christopher Tate44a27902010-01-27 17:15:49 -08005679 // Note that a currently-active backup agent has notified us that it has
5680 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005681 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005682 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005683 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5684 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005685 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005686 op = mCurrentOperations.get(token);
5687 if (op != null) {
5688 op.state = OP_ACKNOWLEDGED;
5689 }
Christopher Tate44a27902010-01-27 17:15:49 -08005690 mCurrentOpLock.notifyAll();
5691 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005692
5693 // The completion callback, if any, is invoked on the handler
5694 if (op != null && op.callback != null) {
5695 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5696 mBackupHandler.sendMessage(msg);
5697 }
Christopher Tate44a27902010-01-27 17:15:49 -08005698 }
5699
Christopher Tate9b3905c2009-06-08 15:24:01 -07005700 // ----- Restore session -----
5701
Christopher Tate80202c82010-01-25 19:37:47 -08005702 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005703 private static final String TAG = "RestoreSession";
5704
Chris Tate44ab8452010-11-16 15:10:49 -08005705 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005706 private IBackupTransport mRestoreTransport = null;
5707 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005708 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005709
Chris Tate44ab8452010-11-16 15:10:49 -08005710 ActiveRestoreSession(String packageName, String transport) {
5711 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005712 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005713 }
5714
5715 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005716 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005717 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005718 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005719 if (observer == null) {
5720 throw new IllegalArgumentException("Observer must not be null");
5721 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005722
Christopher Tate73a3cb32010-12-13 18:27:26 -08005723 if (mEnded) {
5724 throw new IllegalStateException("Restore session already ended");
5725 }
5726
Christopher Tate1bb69062010-02-19 17:02:12 -08005727 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005728 try {
Christopher Tate43383042009-07-13 15:17:13 -07005729 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005730 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005731 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005732 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005733 // spin off the transport request to our service thread
5734 mWakelock.acquire();
5735 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5736 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5737 mBackupHandler.sendMessage(msg);
5738 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005739 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005740 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005741 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005742 } finally {
5743 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005744 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005745 }
5746
Christopher Tate84725812010-02-04 15:52:40 -08005747 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5749 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005750
Chris Tate44ab8452010-11-16 15:10:49 -08005751 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005752 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005753
Christopher Tate73a3cb32010-12-13 18:27:26 -08005754 if (mEnded) {
5755 throw new IllegalStateException("Restore session already ended");
5756 }
5757
Dan Egnor0084da52009-07-29 12:57:16 -07005758 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005759 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5760 return -1;
5761 }
5762
5763 if (mPackageName != null) {
5764 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005765 return -1;
5766 }
5767
Christopher Tate21ab6a52009-09-24 18:01:46 -07005768 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005769 for (int i = 0; i < mRestoreSets.length; i++) {
5770 if (token == mRestoreSets[i].token) {
5771 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005772 mWakelock.acquire();
5773 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005774 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005775 mBackupHandler.sendMessage(msg);
5776 Binder.restoreCallingIdentity(oldId);
5777 return 0;
5778 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005779 }
5780 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005781
Joe Onorato8a9b2202010-02-26 18:56:32 -08005782 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005783 return -1;
5784 }
5785
Christopher Tate284f1bb2011-07-07 14:31:18 -07005786 public synchronized int restoreSome(long token, IRestoreObserver observer,
5787 String[] packages) {
5788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5789 "performRestore");
5790
5791 if (DEBUG) {
5792 StringBuilder b = new StringBuilder(128);
5793 b.append("restoreSome token=");
5794 b.append(Long.toHexString(token));
5795 b.append(" observer=");
5796 b.append(observer.toString());
5797 b.append(" packages=");
5798 if (packages == null) {
5799 b.append("null");
5800 } else {
5801 b.append('{');
5802 boolean first = true;
5803 for (String s : packages) {
5804 if (!first) {
5805 b.append(", ");
5806 } else first = false;
5807 b.append(s);
5808 }
5809 b.append('}');
5810 }
5811 Slog.d(TAG, b.toString());
5812 }
5813
5814 if (mEnded) {
5815 throw new IllegalStateException("Restore session already ended");
5816 }
5817
5818 if (mRestoreTransport == null || mRestoreSets == null) {
5819 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5820 return -1;
5821 }
5822
5823 if (mPackageName != null) {
5824 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5825 return -1;
5826 }
5827
5828 synchronized (mQueueLock) {
5829 for (int i = 0; i < mRestoreSets.length; i++) {
5830 if (token == mRestoreSets[i].token) {
5831 long oldId = Binder.clearCallingIdentity();
5832 mWakelock.acquire();
5833 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5834 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5835 packages, true);
5836 mBackupHandler.sendMessage(msg);
5837 Binder.restoreCallingIdentity(oldId);
5838 return 0;
5839 }
5840 }
5841 }
5842
5843 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5844 return -1;
5845 }
5846
Christopher Tate84725812010-02-04 15:52:40 -08005847 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005848 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005849
Christopher Tate73a3cb32010-12-13 18:27:26 -08005850 if (mEnded) {
5851 throw new IllegalStateException("Restore session already ended");
5852 }
5853
Chris Tate44ab8452010-11-16 15:10:49 -08005854 if (mPackageName != null) {
5855 if (! mPackageName.equals(packageName)) {
5856 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5857 + " on session for package " + mPackageName);
5858 return -1;
5859 }
5860 }
5861
Christopher Tate84725812010-02-04 15:52:40 -08005862 PackageInfo app = null;
5863 try {
5864 app = mPackageManager.getPackageInfo(packageName, 0);
5865 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005866 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005867 return -1;
5868 }
5869
5870 // If the caller is not privileged and is not coming from the target
5871 // app's uid, throw a permission exception back to the caller.
5872 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5873 Binder.getCallingPid(), Binder.getCallingUid());
5874 if ((perm == PackageManager.PERMISSION_DENIED) &&
5875 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005876 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005877 + " or calling uid=" + Binder.getCallingUid());
5878 throw new SecurityException("No permission to restore other packages");
5879 }
5880
Christopher Tate7d411a32010-02-26 11:27:08 -08005881 // If the package has no backup agent, we obviously cannot proceed
5882 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005883 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005884 return -1;
5885 }
5886
Christopher Tate84725812010-02-04 15:52:40 -08005887 // So far so good; we're allowed to try to restore this package. Now
5888 // check whether there is data for it in the current dataset, falling back
5889 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005890 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005891
5892 // If we didn't come up with a place to look -- no ancestral dataset and
5893 // the app has never been backed up from this device -- there's nothing
5894 // to do but return failure.
5895 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005896 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005897 return -1;
5898 }
5899
5900 // Ready to go: enqueue the restore request and claim success
5901 long oldId = Binder.clearCallingIdentity();
5902 mWakelock.acquire();
5903 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005904 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005905 mBackupHandler.sendMessage(msg);
5906 Binder.restoreCallingIdentity(oldId);
5907 return 0;
5908 }
5909
Christopher Tate73a3cb32010-12-13 18:27:26 -08005910 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5911 class EndRestoreRunnable implements Runnable {
5912 BackupManagerService mBackupManager;
5913 ActiveRestoreSession mSession;
5914
5915 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5916 mBackupManager = manager;
5917 mSession = session;
5918 }
5919
5920 public void run() {
5921 // clean up the session's bookkeeping
5922 synchronized (mSession) {
5923 try {
5924 if (mSession.mRestoreTransport != null) {
5925 mSession.mRestoreTransport.finishRestore();
5926 }
5927 } catch (Exception e) {
5928 Slog.e(TAG, "Error in finishRestore", e);
5929 } finally {
5930 mSession.mRestoreTransport = null;
5931 mSession.mEnded = true;
5932 }
5933 }
5934
5935 // clean up the BackupManagerService side of the bookkeeping
5936 // and cancel any pending timeout message
5937 mBackupManager.clearRestoreSession(mSession);
5938 }
5939 }
5940
Dan Egnor0084da52009-07-29 12:57:16 -07005941 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005942 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005943
Christopher Tate73a3cb32010-12-13 18:27:26 -08005944 if (mEnded) {
5945 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005946 }
5947
Christopher Tate73a3cb32010-12-13 18:27:26 -08005948 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005949 }
5950 }
5951
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005952 @Override
5953 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5955
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005956 long identityToken = Binder.clearCallingIdentity();
5957 try {
5958 dumpInternal(pw);
5959 } finally {
5960 Binder.restoreCallingIdentity(identityToken);
5961 }
5962 }
5963
5964 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005965 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005966 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005967 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005968 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005969 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005970 if (mBackupRunning) pw.println("Backup currently running");
5971 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005972 + " (now = " + System.currentTimeMillis() + ')');
5973 pw.println(" next scheduled: " + mNextBackupPass);
5974
Christopher Tate91717492009-06-26 21:07:13 -07005975 pw.println("Available transports:");
5976 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005977 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5978 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005979 IBackupTransport transport = getTransport(t);
5980 File dir = new File(mBaseStateDir, transport.transportDirName());
5981 pw.println(" destination: " + transport.currentDestinationString());
5982 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005983 for (File f : dir.listFiles()) {
5984 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5985 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005986 } catch (Exception e) {
5987 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005988 pw.println(" Error: " + e);
5989 }
Christopher Tate91717492009-06-26 21:07:13 -07005990 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005991
5992 pw.println("Pending init: " + mPendingInits.size());
5993 for (String s : mPendingInits) {
5994 pw.println(" " + s);
5995 }
5996
Christopher Tate6de74ff2012-01-17 15:20:32 -08005997 if (DEBUG_BACKUP_TRACE) {
5998 synchronized (mBackupTrace) {
5999 if (!mBackupTrace.isEmpty()) {
6000 pw.println("Most recent backup trace:");
6001 for (String s : mBackupTrace) {
6002 pw.println(" " + s);
6003 }
6004 }
6005 }
6006 }
6007
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006008 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07006009 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006010 for (int i=0; i<N; i++) {
6011 int uid = mBackupParticipants.keyAt(i);
6012 pw.print(" uid: ");
6013 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07006014 HashSet<String> participants = mBackupParticipants.valueAt(i);
6015 for (String app: participants) {
6016 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006017 }
6018 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006019
Christopher Tateb49ceb32010-02-08 16:22:24 -08006020 pw.println("Ancestral packages: "
6021 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07006022 if (mAncestralPackages != null) {
6023 for (String pkg : mAncestralPackages) {
6024 pw.println(" " + pkg);
6025 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08006026 }
6027
Christopher Tate73e02522009-07-15 14:18:26 -07006028 pw.println("Ever backed up: " + mEverStoredApps.size());
6029 for (String pkg : mEverStoredApps) {
6030 pw.println(" " + pkg);
6031 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006032
6033 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07006034 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07006035 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07006036 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006037 }
6038 }
Christopher Tate487529a2009-04-29 14:03:25 -07006039}