blob: 455d5e9d9f2943ba6c50c050667f062c3bc00676 [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 Tate9ac23d02013-09-19 17:12:27 -07001995 if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) {
1996 // The app has been force-stopped or cleared or just installed,
1997 // and not yet launched out of that state, so just as it won't
1998 // receive broadcasts, we won't run it for backup.
1999 addBackupTrace("skipping - stopped");
2000 executeNextState(BackupState.RUNNING_QUEUE);
2001 return;
2002 }
2003
Christopher Tate043dadc2009-06-02 16:11:00 -07002004 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07002005 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002006 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2007 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07002008 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002009 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07002010 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002011 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2012 // at this point we'll either get a completion callback from the
2013 // agent, or a timeout message on the main handler. either way, we're
2014 // done here as long as we're successful so far.
2015 } else {
2016 // Timeout waiting for the agent
2017 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002018 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002019 } catch (SecurityException ex) {
2020 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002021 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002022 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002023 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002024 }
2025 } catch (NameNotFoundException e) {
2026 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002027 addBackupTrace("no such package");
2028 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002029 } finally {
2030 mWakelock.setWorkSource(null);
2031
2032 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002033 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 if (mStatus != BackupConstants.TRANSPORT_OK) {
2035 BackupState nextState = BackupState.RUNNING_QUEUE;
2036
2037 // An agent-level failure means we reenqueue this one agent for
2038 // a later retry, but otherwise proceed normally.
2039 if (mStatus == BackupConstants.AGENT_ERROR) {
2040 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2041 + " - restaging");
2042 dataChangedImpl(request.packageName);
2043 mStatus = BackupConstants.TRANSPORT_OK;
2044 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002045 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2046 // Failed lookup of the app, so we couldn't bring up an agent, but
2047 // we're otherwise fine. Just drop it and go on to the next as usual.
2048 mStatus = BackupConstants.TRANSPORT_OK;
2049 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002050 // Transport-level failure means we reenqueue everything
2051 revertAndEndBackup();
2052 nextState = BackupState.FINAL;
2053 }
2054
2055 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002056 } else {
2057 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002058 }
2059 }
2060 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002061
Christopher Tate8e294d42011-08-31 20:37:12 -07002062 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002063 addBackupTrace("finishing");
2064
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 // Either backup was successful, in which case we of course do not need
2066 // this pass's journal any more; or it failed, in which case we just
2067 // re-enqueued all of these packages in the current active journal.
2068 // Either way, we no longer need this pass's journal.
2069 if (mJournal != null && !mJournal.delete()) {
2070 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2071 }
2072
2073 // If everything actually went through and this is the first time we've
2074 // done a backup, we can now record what the current backup dataset token
2075 // is.
2076 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002077 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002078 try {
2079 mCurrentToken = mTransport.getCurrentRestoreSet();
2080 } catch (RemoteException e) {} // can't happen
2081 writeRestoreTokens();
2082 }
2083
Christopher Tate336a6492011-10-05 16:05:43 -07002084 // Set up the next backup pass - at this point we can set mBackupRunning
2085 // to false to allow another pass to fire, because we're done with the
2086 // state machine sequence and the wakelock is refcounted.
2087 synchronized (mQueueLock) {
2088 mBackupRunning = false;
2089 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002090 // Make sure we back up everything and perform the one-time init
2091 clearMetadata();
2092 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002093 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002094 backupNow();
2095 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002096 }
2097
2098 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002099 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002100 Slog.i(TAG, "Backup pass finished.");
2101 mWakelock.release();
2102 }
2103
Christopher Tatee659fb92011-10-10 16:34:50 -07002104 // Remove the PM metadata state. This will generate an init on the next pass.
2105 void clearMetadata() {
2106 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2107 if (pmState.exists()) pmState.delete();
2108 }
2109
Christopher Tate8e294d42011-08-31 20:37:12 -07002110 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2111 // handler in case it doesn't get back to us.
2112 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002113 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002114 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2115 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002116
Christopher Tate8e294d42011-08-31 20:37:12 -07002117 mSavedStateName = new File(mStateDir, packageName);
2118 mBackupDataName = new File(mDataDir, packageName + ".data");
2119 mNewStateName = new File(mStateDir, packageName + ".new");
Chris Wrenfd5f5662013-09-19 13:03:53 -04002120 if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002121
Christopher Tate8e294d42011-08-31 20:37:12 -07002122 mSavedState = null;
2123 mBackupData = null;
2124 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002125
Christopher Tate4a627c72011-04-01 14:43:32 -07002126 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127 try {
2128 // Look up the package info & signatures. This is first so that if it
2129 // throws an exception, there's no file setup yet that would need to
2130 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002131 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002132 // The metadata 'package' is synthetic; construct one and make
2133 // sure our global state is pointed at it
2134 mCurrentPackage = new PackageInfo();
2135 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002136 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002137
Christopher Tatec7b31e32009-06-10 15:49:30 -07002138 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002139 // the saved-state "file". This is by definition an incremental,
2140 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002141 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002142 ParcelFileDescriptor.MODE_READ_ONLY |
2143 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002144
Christopher Tate8e294d42011-08-31 20:37:12 -07002145 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002146 ParcelFileDescriptor.MODE_READ_WRITE |
2147 ParcelFileDescriptor.MODE_CREATE |
2148 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002149
rpcraigebab0ae2012-12-04 09:37:23 -05002150 if (!SELinux.restorecon(mBackupDataName)) {
2151 Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2152 }
2153
Christopher Tate8e294d42011-08-31 20:37:12 -07002154 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002155 ParcelFileDescriptor.MODE_READ_WRITE |
2156 ParcelFileDescriptor.MODE_CREATE |
2157 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002158
Christopher Tate44a27902010-01-27 17:15:49 -08002159 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002160 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002161 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002162 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002163 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002164 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002165 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002166 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002167 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2168 e.toString());
2169 agentErrorCleanup();
2170 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002171 }
2172
Christopher Tate8e294d42011-08-31 20:37:12 -07002173 // At this point the agent is off and running. The next thing to happen will
2174 // either be a callback from the agent, at which point we'll process its data
2175 // for transport, or a timeout. Either way the next phase will happen in
2176 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002177 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002178 return BackupConstants.TRANSPORT_OK;
2179 }
2180
2181 @Override
2182 public void operationComplete() {
2183 // Okay, the agent successfully reported back to us. Spin the data off to the
2184 // transport and proceed with the next stage.
2185 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2186 + mCurrentPackage.packageName);
2187 mBackupHandler.removeMessages(MSG_TIMEOUT);
2188 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002190
2191 ParcelFileDescriptor backupData = null;
2192 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002193 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002194 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002195 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002196 if (mStatus == BackupConstants.TRANSPORT_OK) {
2197 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002198 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002199 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002200 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002201 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002202
Dan Egnor83861e72009-09-17 16:17:55 -07002203 // TODO - We call finishBackup() for each application backed up, because
2204 // we need to know now whether it succeeded or failed. Instead, we should
2205 // hold off on finishBackup() until the end, which implies holding off on
2206 // renaming *all* the output state files (see below) until that happens.
2207
Christopher Tate6de74ff2012-01-17 15:20:32 -08002208 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002209 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002210 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002211 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002212 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002213 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002214 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002215 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002216 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002217 }
2218
2219 // After successful transport, delete the now-stale data
2220 // and juggle the files so that next time we supply the agent
2221 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002222 if (mStatus == BackupConstants.TRANSPORT_OK) {
2223 mBackupDataName.delete();
2224 mNewStateName.renameTo(mSavedStateName);
2225 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2226 mCurrentPackage.packageName, size);
2227 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002228 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002229 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2230 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002231 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002232 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002233 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2234 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2235 mCurrentPackage.packageName);
2236 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002237 } finally {
2238 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002239 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002240
Christopher Tate8e294d42011-08-31 20:37:12 -07002241 // If we encountered an error here it's a transport-level failure. That
2242 // means we need to halt everything and reschedule everything for next time.
2243 final BackupState nextState;
2244 if (mStatus != BackupConstants.TRANSPORT_OK) {
2245 revertAndEndBackup();
2246 nextState = BackupState.FINAL;
2247 } else {
2248 // Success! Proceed with the next app if any, otherwise we're done.
2249 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2250 }
2251
2252 executeNextState(nextState);
2253 }
2254
2255 @Override
2256 public void handleTimeout() {
2257 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2258 // it for the next time we run a backup pass.
2259 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2260 // fail repeatedly (i.e. have proved themselves to be buggy).
2261 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2262 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2263 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002264 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002265 agentErrorCleanup();
2266 dataChangedImpl(mCurrentPackage.packageName);
2267 }
2268
2269 void revertAndEndBackup() {
2270 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002271 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002272 for (BackupRequest request : mOriginalQueue) {
2273 dataChangedImpl(request.packageName);
2274 }
2275 // We also want to reset the backup schedule based on whatever
2276 // the transport suggests by way of retry/backoff time.
2277 restartBackupAlarm();
2278 }
2279
2280 void agentErrorCleanup() {
2281 mBackupDataName.delete();
2282 mNewStateName.delete();
2283 clearAgentState();
2284
2285 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2286 }
2287
2288 // Cleanup common to both success and failure cases
2289 void clearAgentState() {
2290 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2291 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2292 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2293 mSavedState = mBackupData = mNewState = null;
2294 synchronized (mCurrentOpLock) {
2295 mCurrentOperations.clear();
2296 }
2297
2298 // If this was a pseudopackage there's no associated Activity Manager state
2299 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002300 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002301 try { // unbind even on timeout, just in case
2302 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2303 } catch (RemoteException e) {}
2304 }
2305 }
2306
2307 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002308 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002309 synchronized (mQueueLock) {
2310 try {
2311 startBackupAlarmsLocked(mTransport.requestBackupTime());
2312 } catch (RemoteException e) { /* cannot happen */ }
2313 }
2314 }
2315
2316 void executeNextState(BackupState nextState) {
2317 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2318 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002319 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002320 mCurrentState = nextState;
2321 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2322 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002323 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002324 }
2325
Christopher Tatedf01dea2009-06-09 20:45:02 -07002326
Christopher Tate294b5122013-02-19 14:08:59 -08002327 // ----- Full backup/restore to a file/socket -----
Christopher Tate4a627c72011-04-01 14:43:32 -07002328
Christopher Tate294b5122013-02-19 14:08:59 -08002329 abstract class ObbServiceClient {
2330 public IObbBackupService mObbService;
2331 public void setObbBinder(IObbBackupService binder) {
2332 mObbService = binder;
2333 }
2334 }
2335
2336 class FullBackupObbConnection implements ServiceConnection {
2337 volatile IObbBackupService mService;
2338
2339 FullBackupObbConnection() {
2340 mService = null;
2341 }
2342
2343 public void establish() {
2344 if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2345 Intent obbIntent = new Intent().setComponent(new ComponentName(
2346 "com.android.sharedstoragebackup",
2347 "com.android.sharedstoragebackup.ObbBackupService"));
2348 BackupManagerService.this.mContext.bindService(
2349 obbIntent, this, Context.BIND_AUTO_CREATE);
2350 }
2351
2352 public void tearDown() {
2353 BackupManagerService.this.mContext.unbindService(this);
2354 }
2355
2356 public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2357 boolean success = false;
2358 waitForConnection();
2359
2360 ParcelFileDescriptor[] pipes = null;
2361 try {
2362 pipes = ParcelFileDescriptor.createPipe();
2363 int token = generateToken();
2364 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2365 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2366 routeSocketDataToOutput(pipes[0], out);
2367 success = waitUntilOperationComplete(token);
2368 } catch (Exception e) {
2369 Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2370 } finally {
2371 try {
2372 out.flush();
2373 if (pipes != null) {
2374 if (pipes[0] != null) pipes[0].close();
2375 if (pipes[1] != null) pipes[1].close();
2376 }
2377 } catch (IOException e) {
2378 Slog.w(TAG, "I/O error closing down OBB backup", e);
2379 }
2380 }
2381 return success;
2382 }
2383
2384 public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2385 long fileSize, int type, String path, long mode, long mtime,
2386 int token, IBackupManager callbackBinder) {
2387 waitForConnection();
2388
2389 try {
2390 mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2391 token, callbackBinder);
2392 } catch (Exception e) {
2393 Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2394 }
2395 }
2396
2397 private void waitForConnection() {
2398 synchronized (this) {
2399 while (mService == null) {
2400 if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2401 try {
2402 this.wait();
2403 } catch (InterruptedException e) { /* never interrupted */ }
2404 }
2405 if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2406 }
2407 }
2408
2409 @Override
2410 public void onServiceConnected(ComponentName name, IBinder service) {
2411 synchronized (this) {
2412 mService = IObbBackupService.Stub.asInterface(service);
2413 if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2414 + " connected on " + this);
2415 this.notifyAll();
2416 }
2417 }
2418
2419 @Override
2420 public void onServiceDisconnected(ComponentName name) {
2421 synchronized (this) {
2422 mService = null;
2423 if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2424 this.notifyAll();
2425 }
2426 }
2427
2428 }
2429
2430 private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2431 throws IOException {
2432 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2433 DataInputStream in = new DataInputStream(raw);
2434
2435 byte[] buffer = new byte[32 * 1024];
2436 int chunkTotal;
2437 while ((chunkTotal = in.readInt()) > 0) {
2438 while (chunkTotal > 0) {
2439 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2440 int nRead = in.read(buffer, 0, toRead);
2441 out.write(buffer, 0, nRead);
2442 chunkTotal -= nRead;
2443 }
2444 }
2445 }
2446
2447 class PerformFullBackupTask extends ObbServiceClient implements Runnable {
Christopher Tate4a627c72011-04-01 14:43:32 -07002448 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002449 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002450 IFullBackupRestoreObserver mObserver;
2451 boolean mIncludeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002452 boolean mIncludeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002453 boolean mIncludeShared;
2454 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002455 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002456 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002457 String mCurrentPassword;
2458 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002459 AtomicBoolean mLatchObject;
2460 File mFilesDir;
2461 File mManifestFile;
Christopher Tate294b5122013-02-19 14:08:59 -08002462
Christopher Tate4a627c72011-04-01 14:43:32 -07002463
Christopher Tate7926a692011-07-11 11:31:57 -07002464 class FullBackupRunner implements Runnable {
2465 PackageInfo mPackage;
2466 IBackupAgent mAgent;
2467 ParcelFileDescriptor mPipe;
2468 int mToken;
2469 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002470 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002471
2472 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002473 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002474 mPackage = pack;
2475 mAgent = agent;
2476 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2477 mToken = token;
2478 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002479 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002480 }
2481
2482 @Override
2483 public void run() {
2484 try {
2485 BackupDataOutput output = new BackupDataOutput(
2486 mPipe.getFileDescriptor());
2487
Christopher Tate73d73692012-01-20 17:11:31 -08002488 if (mWriteManifest) {
2489 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2490 writeAppManifest(mPackage, mManifestFile, mSendApk);
2491 FullBackup.backupToTar(mPackage.packageName, null, null,
2492 mFilesDir.getAbsolutePath(),
2493 mManifestFile.getAbsolutePath(),
2494 output);
2495 }
Christopher Tate7926a692011-07-11 11:31:57 -07002496
2497 if (mSendApk) {
2498 writeApkToBackup(mPackage, output);
2499 }
2500
Christopher Tatec58efa62011-08-01 19:20:14 -07002501 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002502 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002503 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2504 } catch (IOException e) {
2505 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2506 } catch (RemoteException e) {
2507 Slog.e(TAG, "Remote agent vanished during full backup of "
2508 + mPackage.packageName);
2509 } finally {
2510 try {
2511 mPipe.close();
2512 } catch (IOException e) {}
2513 }
2514 }
2515 }
2516
Christopher Tate4a627c72011-04-01 14:43:32 -07002517 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate294b5122013-02-19 14:08:59 -08002518 boolean includeApks, boolean includeObbs, boolean includeShared,
2519 String curPassword, String encryptPassword, boolean doAllApps,
2520 boolean doSystem, String[] packages, AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002521 mOutputFile = fd;
2522 mObserver = observer;
2523 mIncludeApks = includeApks;
Christopher Tate294b5122013-02-19 14:08:59 -08002524 mIncludeObbs = includeObbs;
Christopher Tate4a627c72011-04-01 14:43:32 -07002525 mIncludeShared = includeShared;
2526 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002527 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002528 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002529 mCurrentPassword = curPassword;
2530 // when backing up, if there is a current backup password, we require that
2531 // the user use a nonempty encryption password as well. if one is supplied
2532 // in the UI we use that, but if the UI was left empty we fall back to the
2533 // current backup password (which was supplied by the user as well).
2534 if (encryptPassword == null || "".equals(encryptPassword)) {
2535 mEncryptPassword = curPassword;
2536 } else {
2537 mEncryptPassword = encryptPassword;
2538 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002539 mLatchObject = latch;
2540
2541 mFilesDir = new File("/data/system");
2542 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2543 }
2544
2545 @Override
2546 public void run() {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002547 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate294b5122013-02-19 14:08:59 -08002548
2549 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
2550 FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2551 obbConnection.establish(); // we'll want this later
2552
Christopher Tate4a627c72011-04-01 14:43:32 -07002553 sendStartBackup();
2554
2555 // doAllApps supersedes the package set if any
2556 if (mAllApps) {
2557 packagesToBackup = mPackageManager.getInstalledPackages(
2558 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002559 // Exclude system apps if we've been asked to do so
2560 if (mIncludeSystem == false) {
2561 for (int i = 0; i < packagesToBackup.size(); ) {
2562 PackageInfo pkg = packagesToBackup.get(i);
2563 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2564 packagesToBackup.remove(i);
2565 } else {
2566 i++;
2567 }
2568 }
2569 }
2570 }
2571
2572 // Now process the command line argument packages, if any. Note that explicitly-
2573 // named system-partition packages will be included even if includeSystem was
2574 // set to false.
2575 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002576 for (String pkgName : mPackages) {
2577 try {
2578 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2579 PackageManager.GET_SIGNATURES));
2580 } catch (NameNotFoundException e) {
2581 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2582 }
2583 }
2584 }
2585
Christopher Tate73d73692012-01-20 17:11:31 -08002586 // Cull any packages that have indicated that backups are not permitted, as well
2587 // as any explicit mention of the 'special' shared-storage agent package (we
2588 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002589 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002590 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002591 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2592 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002593 packagesToBackup.remove(i);
2594 } else {
2595 i++;
2596 }
2597 }
2598
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002599 // Cull any packages that run as system-domain uids but do not define their
2600 // own backup agents
2601 for (int i = 0; i < packagesToBackup.size(); ) {
2602 PackageInfo pkg = packagesToBackup.get(i);
2603 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2604 && (pkg.applicationInfo.backupAgentName == null)) {
2605 if (MORE_DEBUG) {
2606 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2607 }
2608 packagesToBackup.remove(i);
2609 } else {
2610 i++;
2611 }
2612 }
2613
Christopher Tate7926a692011-07-11 11:31:57 -07002614 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002615 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002616
Christopher Tate4a627c72011-04-01 14:43:32 -07002617 PackageInfo pkg = null;
2618 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002619 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002620 boolean compressing = COMPRESS_FULL_BACKUPS;
2621 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002622
Christopher Tateeef4ae42011-08-05 13:15:53 -07002623 // Verify that the given password matches the currently-active
2624 // backup password, if any
2625 if (hasBackupPassword()) {
2626 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2627 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2628 return;
2629 }
2630 }
2631
Christopher Tate7bdb0962011-07-13 19:30:21 -07002632 // Write the global file header. All strings are UTF-8 encoded; lines end
2633 // with a '\n' byte. Actual backup data begins immediately following the
2634 // final '\n'.
2635 //
2636 // line 1: "ANDROID BACKUP"
2637 // line 2: backup file format version, currently "1"
2638 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002639 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2640 //
2641 // When line 4 is not "none", then additional header data follows:
2642 //
2643 // line 5: user password salt [hex]
2644 // line 6: master key checksum salt [hex]
2645 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2646 // line 8: IV of the user key [hex]
2647 // line 9: master key blob [hex]
2648 // IV of the master key, master key itself, master key checksum hash
2649 //
2650 // The master key checksum is the master key plus its checksum salt, run through
2651 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2652 // correct password for decrypting the archive: the master key decrypted from
2653 // the archive using the user-supplied password is also run through PBKDF2 in
2654 // this way, and if the result does not match the checksum as stored in the
2655 // archive, then we know that the user-supplied password does not match the
2656 // archive's.
2657 StringBuilder headerbuf = new StringBuilder(1024);
2658
Christopher Tate7bdb0962011-07-13 19:30:21 -07002659 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002660 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2661 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002662
2663 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002664 // Set up the encryption stage if appropriate, and emit the correct header
2665 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002666 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2667 } else {
2668 headerbuf.append("none\n");
2669 }
2670
Christopher Tate7bdb0962011-07-13 19:30:21 -07002671 byte[] header = headerbuf.toString().getBytes("UTF-8");
2672 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002673
2674 // Set up the compression stage feeding into the encryption stage (if any)
2675 if (compressing) {
2676 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2677 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2678 }
2679
2680 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002681 } catch (Exception e) {
2682 // Should never happen!
2683 Slog.e(TAG, "Unable to emit archive header", e);
2684 return;
2685 }
2686
Christopher Tate73d73692012-01-20 17:11:31 -08002687 // Shared storage if requested
2688 if (mIncludeShared) {
2689 try {
2690 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2691 packagesToBackup.add(pkg);
2692 } catch (NameNotFoundException e) {
2693 Slog.e(TAG, "Unable to find shared-storage backup handler");
2694 }
2695 }
2696
Christopher Tateb0628bf2011-06-02 15:08:13 -07002697 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002698 int N = packagesToBackup.size();
2699 for (int i = 0; i < N; i++) {
2700 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002701 backupOnePackage(pkg, out);
Christopher Tate294b5122013-02-19 14:08:59 -08002702
2703 // after the app's agent runs to handle its private filesystem
2704 // contents, back up any OBB content it has on its behalf.
2705 if (mIncludeObbs) {
2706 boolean obbOkay = obbConnection.backupObbs(pkg, out);
2707 if (!obbOkay) {
2708 throw new RuntimeException("Failure writing OBB stack for " + pkg);
2709 }
2710 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002711 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002712
Christopher Tate6853fcf2011-08-10 17:52:21 -07002713 // Done!
2714 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002715 } catch (RemoteException e) {
2716 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002717 } catch (Exception e) {
2718 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002719 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002720 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002721 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002722 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002723 mOutputFile.close();
2724 } catch (IOException e) {
2725 /* nothing we can do about this */
2726 }
2727 synchronized (mCurrentOpLock) {
2728 mCurrentOperations.clear();
2729 }
2730 synchronized (mLatchObject) {
2731 mLatchObject.set(true);
2732 mLatchObject.notifyAll();
2733 }
2734 sendEndBackup();
Christopher Tate294b5122013-02-19 14:08:59 -08002735 obbConnection.tearDown();
Christopher Tate4a627c72011-04-01 14:43:32 -07002736 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002737 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002738 }
2739 }
2740
Christopher Tate2efd2db2011-07-19 16:32:49 -07002741 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2742 OutputStream ofstream) throws Exception {
2743 // User key will be used to encrypt the master key.
2744 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002745 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002746 PBKDF2_HASH_ROUNDS);
2747
2748 // the master key is random for each backup
2749 byte[] masterPw = new byte[256 / 8];
2750 mRng.nextBytes(masterPw);
2751 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2752
2753 // primary encryption of the datastream with the random key
2754 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2755 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2756 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2757 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2758
2759 // line 4: name of encryption algorithm
2760 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2761 headerbuf.append('\n');
2762 // line 5: user password salt [hex]
2763 headerbuf.append(byteArrayToHex(newUserSalt));
2764 headerbuf.append('\n');
2765 // line 6: master key checksum salt [hex]
2766 headerbuf.append(byteArrayToHex(checksumSalt));
2767 headerbuf.append('\n');
2768 // line 7: number of PBKDF2 rounds used [decimal]
2769 headerbuf.append(PBKDF2_HASH_ROUNDS);
2770 headerbuf.append('\n');
2771
2772 // line 8: IV of the user key [hex]
2773 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2774 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2775
2776 byte[] IV = mkC.getIV();
2777 headerbuf.append(byteArrayToHex(IV));
2778 headerbuf.append('\n');
2779
2780 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2781 // [byte] IV length = Niv
2782 // [array of Niv bytes] IV itself
2783 // [byte] master key length = Nmk
2784 // [array of Nmk bytes] master key itself
2785 // [byte] MK checksum hash length = Nck
2786 // [array of Nck bytes] master key checksum hash
2787 //
2788 // The checksum is the (master key + checksum salt), run through the
2789 // stated number of PBKDF2 rounds
2790 IV = c.getIV();
2791 byte[] mk = masterKeySpec.getEncoded();
2792 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2793 checksumSalt, PBKDF2_HASH_ROUNDS);
2794
2795 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2796 + checksum.length + 3);
2797 DataOutputStream mkOut = new DataOutputStream(blob);
2798 mkOut.writeByte(IV.length);
2799 mkOut.write(IV);
2800 mkOut.writeByte(mk.length);
2801 mkOut.write(mk);
2802 mkOut.writeByte(checksum.length);
2803 mkOut.write(checksum);
2804 mkOut.flush();
2805 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2806 headerbuf.append(byteArrayToHex(encryptedMk));
2807 headerbuf.append('\n');
2808
2809 return finalOutput;
2810 }
2811
2812 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002813 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002814 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2815
2816 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2817 IApplicationThread.BACKUP_MODE_FULL);
2818 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002819 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002820 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002821 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002822
Christopher Tateb0628bf2011-06-02 15:08:13 -07002823 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002824 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002825 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002826 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002827 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2828 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2829 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2830
Christopher Tate73d73692012-01-20 17:11:31 -08002831 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002832
Christopher Tate7926a692011-07-11 11:31:57 -07002833 final int token = generateToken();
2834 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002835 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002836 pipes[1].close(); // the runner has dup'd it
2837 pipes[1] = null;
2838 Thread t = new Thread(runner);
2839 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002840
Christopher Tate7926a692011-07-11 11:31:57 -07002841 // Now pull data from the app and stuff it into the compressor
2842 try {
Christopher Tate294b5122013-02-19 14:08:59 -08002843 routeSocketDataToOutput(pipes[0], out);
Christopher Tate7926a692011-07-11 11:31:57 -07002844 } catch (IOException e) {
2845 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002846 }
2847
Christopher Tateb0628bf2011-06-02 15:08:13 -07002848 if (!waitUntilOperationComplete(token)) {
2849 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2850 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002851 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002852 }
Christopher Tate7926a692011-07-11 11:31:57 -07002853
Christopher Tateb0628bf2011-06-02 15:08:13 -07002854 } catch (IOException e) {
2855 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002856 } finally {
2857 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002858 // flush after every package
2859 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002860 if (pipes != null) {
2861 if (pipes[0] != null) pipes[0].close();
2862 if (pipes[1] != null) pipes[1].close();
2863 }
Christopher Tate7926a692011-07-11 11:31:57 -07002864 } catch (IOException e) {
2865 Slog.w(TAG, "Error bringing down backup stack");
2866 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002867 }
2868 } else {
2869 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2870 }
2871 tearDown(pkg);
2872 }
2873
Christopher Tate79ec80d2011-06-24 14:58:49 -07002874 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2875 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2876 final String appSourceDir = pkg.applicationInfo.sourceDir;
2877 final String apkDir = new File(appSourceDir).getParent();
2878 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2879 apkDir, appSourceDir, output);
2880
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002881 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2882 // doesn't have access to external storage.
2883
Christopher Tate79ec80d2011-06-24 14:58:49 -07002884 // Save associated .obb content if it exists and we did save the apk
2885 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002886 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002887 final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
Christopher Tate79ec80d2011-06-24 14:58:49 -07002888 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002889 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002890 File[] obbFiles = obbDir.listFiles();
2891 if (obbFiles != null) {
2892 final String obbDirName = obbDir.getAbsolutePath();
2893 for (File obb : obbFiles) {
2894 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2895 obbDirName, obb.getAbsolutePath(), output);
2896 }
2897 }
2898 }
2899 }
2900
Christopher Tate6853fcf2011-08-10 17:52:21 -07002901 private void finalizeBackup(OutputStream out) {
2902 try {
2903 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2904 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2905 out.write(eof);
2906 } catch (IOException e) {
2907 Slog.w(TAG, "Error attempting to finalize backup stream");
2908 }
2909 }
2910
Christopher Tate4a627c72011-04-01 14:43:32 -07002911 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2912 throws IOException {
2913 // Manifest format. All data are strings ending in LF:
2914 // BACKUP_MANIFEST_VERSION, currently 1
2915 //
2916 // Version 1:
2917 // package name
2918 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002919 // platform versionCode
2920 // getInstallerPackageName() for this package (maybe empty)
2921 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002922 // number of signatures == N
2923 // N*: signature byte array in ascii format per Signature.toCharsString()
2924 StringBuilder builder = new StringBuilder(4096);
2925 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2926
2927 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2928 printer.println(pkg.packageName);
2929 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002930 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2931
2932 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2933 printer.println((installerName != null) ? installerName : "");
2934
Christopher Tate4a627c72011-04-01 14:43:32 -07002935 printer.println(withApk ? "1" : "0");
2936 if (pkg.signatures == null) {
2937 printer.println("0");
2938 } else {
2939 printer.println(Integer.toString(pkg.signatures.length));
2940 for (Signature sig : pkg.signatures) {
2941 printer.println(sig.toCharsString());
2942 }
2943 }
2944
2945 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002946 outstream.write(builder.toString().getBytes());
2947 outstream.close();
2948 }
2949
2950 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002951 if (pkg != null) {
2952 final ApplicationInfo app = pkg.applicationInfo;
2953 if (app != null) {
2954 try {
2955 // unbind and tidy up even on timeout or failure, just in case
2956 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002957
Christopher Tateb0628bf2011-06-02 15:08:13 -07002958 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002959 if (app.uid != Process.SYSTEM_UID
2960 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002961 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002962 mActivityManager.killApplicationProcess(app.processName, app.uid);
2963 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002964 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002965 }
2966 } catch (RemoteException e) {
2967 Slog.d(TAG, "Lost app trying to shut down");
2968 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002969 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002970 }
2971 }
2972
2973 // wrappers for observer use
2974 void sendStartBackup() {
2975 if (mObserver != null) {
2976 try {
2977 mObserver.onStartBackup();
2978 } catch (RemoteException e) {
2979 Slog.w(TAG, "full backup observer went away: startBackup");
2980 mObserver = null;
2981 }
2982 }
2983 }
2984
2985 void sendOnBackupPackage(String name) {
2986 if (mObserver != null) {
2987 try {
2988 // TODO: use a more user-friendly name string
2989 mObserver.onBackupPackage(name);
2990 } catch (RemoteException e) {
2991 Slog.w(TAG, "full backup observer went away: backupPackage");
2992 mObserver = null;
2993 }
2994 }
2995 }
2996
2997 void sendEndBackup() {
2998 if (mObserver != null) {
2999 try {
3000 mObserver.onEndBackup();
3001 } catch (RemoteException e) {
3002 Slog.w(TAG, "full backup observer went away: endBackup");
3003 mObserver = null;
3004 }
3005 }
3006 }
3007 }
3008
3009
Christopher Tate75a99702011-05-18 16:28:19 -07003010 // ----- Full restore from a file/socket -----
3011
3012 // Description of a file in the restore datastream
3013 static class FileMetadata {
3014 String packageName; // name of the owning app
3015 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07003016 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07003017 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
3018 String path; // subpath within the semantic domain
3019 long mode; // e.g. 0666 (actually int)
3020 long mtime; // last mod time, UTC time_t (actually int)
3021 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003022
3023 @Override
3024 public String toString() {
3025 StringBuilder sb = new StringBuilder(128);
3026 sb.append("FileMetadata{");
3027 sb.append(packageName); sb.append(',');
3028 sb.append(type); sb.append(',');
3029 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3030 sb.append(size);
3031 sb.append('}');
3032 return sb.toString();
3033 }
Christopher Tate75a99702011-05-18 16:28:19 -07003034 }
3035
3036 enum RestorePolicy {
3037 IGNORE,
3038 ACCEPT,
3039 ACCEPT_IF_APK
3040 }
3041
Christopher Tate294b5122013-02-19 14:08:59 -08003042 class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
Christopher Tate75a99702011-05-18 16:28:19 -07003043 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07003044 String mCurrentPassword;
3045 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003046 IFullBackupRestoreObserver mObserver;
3047 AtomicBoolean mLatchObject;
3048 IBackupAgent mAgent;
3049 String mAgentPackage;
3050 ApplicationInfo mTargetApp;
Christopher Tate294b5122013-02-19 14:08:59 -08003051 FullBackupObbConnection mObbConnection = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003052 ParcelFileDescriptor[] mPipes = null;
3053
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003054 long mBytes;
3055
Christopher Tate75a99702011-05-18 16:28:19 -07003056 // possible handling states for a given package in the restore dataset
3057 final HashMap<String, RestorePolicy> mPackagePolicies
3058 = new HashMap<String, RestorePolicy>();
3059
3060 // installer package names for each encountered app, derived from the manifests
3061 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3062
3063 // Signatures for a given package found in its manifest file
3064 final HashMap<String, Signature[]> mManifestSignatures
3065 = new HashMap<String, Signature[]>();
3066
3067 // Packages we've already wiped data on when restoring their first file
3068 final HashSet<String> mClearedPackages = new HashSet<String>();
3069
Christopher Tate728a1c42011-07-28 18:03:03 -07003070 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003071 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07003072 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07003073 mCurrentPassword = curPassword;
3074 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07003075 mObserver = observer;
3076 mLatchObject = latch;
3077 mAgent = null;
3078 mAgentPackage = null;
3079 mTargetApp = null;
Christopher Tate294b5122013-02-19 14:08:59 -08003080 mObbConnection = new FullBackupObbConnection();
Christopher Tate75a99702011-05-18 16:28:19 -07003081
3082 // Which packages we've already wiped data on. We prepopulate this
3083 // with a whitelist of packages known to be unclearable.
3084 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07003085 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07003086
Christopher Tate75a99702011-05-18 16:28:19 -07003087 }
3088
3089 class RestoreFileRunnable implements Runnable {
3090 IBackupAgent mAgent;
3091 FileMetadata mInfo;
3092 ParcelFileDescriptor mSocket;
3093 int mToken;
3094
3095 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3096 ParcelFileDescriptor socket, int token) throws IOException {
3097 mAgent = agent;
3098 mInfo = info;
3099 mToken = token;
3100
3101 // This class is used strictly for process-local binder invocations. The
3102 // semantics of ParcelFileDescriptor differ in this case; in particular, we
3103 // do not automatically get a 'dup'ed descriptor that we can can continue
3104 // to use asynchronously from the caller. So, we make sure to dup it ourselves
3105 // before proceeding to do the restore.
3106 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3107 }
3108
3109 @Override
3110 public void run() {
3111 try {
3112 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3113 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3114 mToken, mBackupManagerBinder);
3115 } catch (RemoteException e) {
3116 // never happens; this is used strictly for local binder calls
3117 }
3118 }
3119 }
3120
3121 @Override
3122 public void run() {
3123 Slog.i(TAG, "--- Performing full-dataset restore ---");
Christopher Tate294b5122013-02-19 14:08:59 -08003124 mObbConnection.establish();
Christopher Tate75a99702011-05-18 16:28:19 -07003125 sendStartRestore();
3126
Christopher Tateb0628bf2011-06-02 15:08:13 -07003127 // Are we able to restore shared-storage data?
3128 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08003129 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07003130 }
3131
Christopher Tate2efd2db2011-07-19 16:32:49 -07003132 FileInputStream rawInStream = null;
3133 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003134 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07003135 if (hasBackupPassword()) {
3136 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
3137 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3138 return;
3139 }
3140 }
3141
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003142 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003143 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003144 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3145 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003146
3147 // First, parse out the unencrypted/uncompressed header
3148 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003149 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003150 final InputStream in;
3151
3152 boolean okay = false;
3153 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3154 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003155 rawDataIn.readFully(streamHeader);
3156 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3157 if (Arrays.equals(magicBytes, streamHeader)) {
3158 // okay, header looks good. now parse out the rest of the fields.
3159 String s = readHeaderLine(rawInStream);
3160 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3161 // okay, it's a version we recognize
3162 s = readHeaderLine(rawInStream);
3163 compressed = (Integer.parseInt(s) != 0);
3164 s = readHeaderLine(rawInStream);
3165 if (s.equals("none")) {
3166 // no more header to parse; we're good to go
3167 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003168 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003169 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3170 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003171 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003172 }
3173 } else Slog.w(TAG, "Archive is encrypted but no password given");
3174 } else Slog.w(TAG, "Wrong header version: " + s);
3175 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003176
3177 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003178 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003179 return;
3180 }
3181
3182 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003183 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003184
3185 boolean didRestore;
3186 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003187 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003188 } while (didRestore);
3189
Christopher Tatec58efa62011-08-01 19:20:14 -07003190 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003191 } catch (IOException e) {
3192 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003193 } finally {
3194 tearDownPipes();
3195 tearDownAgent(mTargetApp);
3196
3197 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003198 if (rawDataIn != null) rawDataIn.close();
3199 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003200 mInputFile.close();
3201 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003202 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003203 /* nothing we can do about this */
3204 }
3205 synchronized (mCurrentOpLock) {
3206 mCurrentOperations.clear();
3207 }
3208 synchronized (mLatchObject) {
3209 mLatchObject.set(true);
3210 mLatchObject.notifyAll();
3211 }
Christopher Tate294b5122013-02-19 14:08:59 -08003212 mObbConnection.tearDown();
Christopher Tate75a99702011-05-18 16:28:19 -07003213 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003214 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003215 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003216 }
3217 }
3218
Christopher Tate7bdb0962011-07-13 19:30:21 -07003219 String readHeaderLine(InputStream in) throws IOException {
3220 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003221 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003222 while ((c = in.read()) >= 0) {
3223 if (c == '\n') break; // consume and discard the newlines
3224 buffer.append((char)c);
3225 }
3226 return buffer.toString();
3227 }
3228
Christopher Tate2efd2db2011-07-19 16:32:49 -07003229 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3230 InputStream result = null;
3231 try {
3232 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3233
3234 String userSaltHex = readHeaderLine(rawInStream); // 5
3235 byte[] userSalt = hexToByteArray(userSaltHex);
3236
3237 String ckSaltHex = readHeaderLine(rawInStream); // 6
3238 byte[] ckSalt = hexToByteArray(ckSaltHex);
3239
3240 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3241 String userIvHex = readHeaderLine(rawInStream); // 8
3242
3243 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3244
3245 // decrypt the master key blob
3246 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003247 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003248 rounds);
3249 byte[] IV = hexToByteArray(userIvHex);
3250 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3251 c.init(Cipher.DECRYPT_MODE,
3252 new SecretKeySpec(userKey.getEncoded(), "AES"),
3253 ivSpec);
3254 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3255 byte[] mkBlob = c.doFinal(mkCipher);
3256
3257 // first, the master key IV
3258 int offset = 0;
3259 int len = mkBlob[offset++];
3260 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3261 offset += len;
3262 // then the master key itself
3263 len = mkBlob[offset++];
3264 byte[] mk = Arrays.copyOfRange(mkBlob,
3265 offset, offset + len);
3266 offset += len;
3267 // and finally the master key checksum hash
3268 len = mkBlob[offset++];
3269 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3270 offset, offset + len);
3271
3272 // now validate the decrypted master key against the checksum
3273 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3274 if (Arrays.equals(calculatedCk, mkChecksum)) {
3275 ivSpec = new IvParameterSpec(IV);
3276 c.init(Cipher.DECRYPT_MODE,
3277 new SecretKeySpec(mk, "AES"),
3278 ivSpec);
3279 // Only if all of the above worked properly will 'result' be assigned
3280 result = new CipherInputStream(rawInStream, c);
3281 } else Slog.w(TAG, "Incorrect password");
3282 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3283 } catch (InvalidAlgorithmParameterException e) {
3284 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3285 } catch (BadPaddingException e) {
3286 // This case frequently occurs when the wrong password is used to decrypt
3287 // the master key. Use the identical "incorrect password" log text as is
3288 // used in the checksum failure log in order to avoid providing additional
3289 // information to an attacker.
3290 Slog.w(TAG, "Incorrect password");
3291 } catch (IllegalBlockSizeException e) {
3292 Slog.w(TAG, "Invalid block size in master key");
3293 } catch (NoSuchAlgorithmException e) {
3294 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3295 } catch (NoSuchPaddingException e) {
3296 Slog.e(TAG, "Needed padding mechanism unavailable!");
3297 } catch (InvalidKeyException e) {
3298 Slog.w(TAG, "Illegal password; aborting");
3299 } catch (NumberFormatException e) {
3300 Slog.w(TAG, "Can't parse restore data header");
3301 } catch (IOException e) {
3302 Slog.w(TAG, "Can't read input header");
3303 }
3304
3305 return result;
3306 }
3307
Christopher Tate75a99702011-05-18 16:28:19 -07003308 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3309 FileMetadata info;
3310 try {
3311 info = readTarHeaders(instream);
3312 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003313 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003314 dumpFileMetadata(info);
3315 }
3316
3317 final String pkg = info.packageName;
3318 if (!pkg.equals(mAgentPackage)) {
3319 // okay, change in package; set up our various
3320 // bookkeeping if we haven't seen it yet
3321 if (!mPackagePolicies.containsKey(pkg)) {
3322 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3323 }
3324
3325 // Clean up the previous agent relationship if necessary,
3326 // and let the observer know we're considering a new app.
3327 if (mAgent != null) {
3328 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3329 tearDownPipes();
3330 tearDownAgent(mTargetApp);
3331 mTargetApp = null;
3332 mAgentPackage = null;
3333 }
3334 }
3335
3336 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3337 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3338 mPackageInstallers.put(pkg, info.installerPackageName);
3339 // We've read only the manifest content itself at this point,
3340 // so consume the footer before looping around to the next
3341 // input file
3342 skipTarPadding(info.size, instream);
3343 sendOnRestorePackage(pkg);
3344 } else {
3345 // Non-manifest, so it's actual file data. Is this a package
3346 // we're ignoring?
3347 boolean okay = true;
3348 RestorePolicy policy = mPackagePolicies.get(pkg);
3349 switch (policy) {
3350 case IGNORE:
3351 okay = false;
3352 break;
3353
3354 case ACCEPT_IF_APK:
3355 // If we're in accept-if-apk state, then the first file we
3356 // see MUST be the apk.
3357 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3358 if (DEBUG) Slog.d(TAG, "APK file; installing");
3359 // Try to install the app.
3360 String installerName = mPackageInstallers.get(pkg);
3361 okay = installApk(info, installerName, instream);
3362 // good to go; promote to ACCEPT
3363 mPackagePolicies.put(pkg, (okay)
3364 ? RestorePolicy.ACCEPT
3365 : RestorePolicy.IGNORE);
3366 // At this point we've consumed this file entry
3367 // ourselves, so just strip the tar footer and
3368 // go on to the next file in the input stream
3369 skipTarPadding(info.size, instream);
3370 return true;
3371 } else {
3372 // File data before (or without) the apk. We can't
3373 // handle it coherently in this case so ignore it.
3374 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3375 okay = false;
3376 }
3377 break;
3378
3379 case ACCEPT:
3380 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3381 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3382 // we can take the data without the apk, so we
3383 // *want* to do so. skip the apk by declaring this
3384 // one file not-okay without changing the restore
3385 // policy for the package.
3386 okay = false;
3387 }
3388 break;
3389
3390 default:
3391 // Something has gone dreadfully wrong when determining
3392 // the restore policy from the manifest. Ignore the
3393 // rest of this package's data.
3394 Slog.e(TAG, "Invalid policy from manifest");
3395 okay = false;
3396 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3397 break;
3398 }
3399
3400 // If the policy is satisfied, go ahead and set up to pipe the
3401 // data to the agent.
3402 if (DEBUG && okay && mAgent != null) {
3403 Slog.i(TAG, "Reusing existing agent instance");
3404 }
3405 if (okay && mAgent == null) {
3406 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3407
3408 try {
3409 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3410
3411 // If we haven't sent any data to this app yet, we probably
3412 // need to clear it first. Check that.
3413 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003414 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003415 // responsible for coherently managing a full
3416 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003417 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003418 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3419 clearApplicationDataSynchronous(pkg);
3420 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003421 if (DEBUG) Slog.d(TAG, "backup agent ("
3422 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003423 }
3424 mClearedPackages.add(pkg);
3425 } else {
3426 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3427 }
3428
3429 // All set; now set up the IPC and launch the agent
3430 setUpPipes();
3431 mAgent = bindToAgentSynchronous(mTargetApp,
3432 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3433 mAgentPackage = pkg;
3434 } catch (IOException e) {
3435 // fall through to error handling
3436 } catch (NameNotFoundException e) {
3437 // fall through to error handling
3438 }
3439
3440 if (mAgent == null) {
3441 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3442 okay = false;
3443 tearDownPipes();
3444 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3445 }
3446 }
3447
3448 // Sanity check: make sure we never give data to the wrong app. This
3449 // should never happen but a little paranoia here won't go amiss.
3450 if (okay && !pkg.equals(mAgentPackage)) {
3451 Slog.e(TAG, "Restoring data for " + pkg
3452 + " but agent is for " + mAgentPackage);
3453 okay = false;
3454 }
3455
3456 // At this point we have an agent ready to handle the full
3457 // restore data as well as a pipe for sending data to
3458 // that agent. Tell the agent to start reading from the
3459 // pipe.
3460 if (okay) {
3461 boolean agentSuccess = true;
3462 long toCopy = info.size;
3463 final int token = generateToken();
3464 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07003465 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate294b5122013-02-19 14:08:59 -08003466 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3467 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3468 + " : " + info.path);
3469 mObbConnection.restoreObbFile(pkg, mPipes[0],
3470 info.size, info.type, info.path, info.mode,
3471 info.mtime, token, mBackupManagerBinder);
Christopher Tate75a99702011-05-18 16:28:19 -07003472 } else {
Christopher Tate294b5122013-02-19 14:08:59 -08003473 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3474 + info.path);
3475 // fire up the app's agent listening on the socket. If
3476 // the agent is running in the system process we can't
3477 // just invoke it asynchronously, so we provide a thread
3478 // for it here.
3479 if (mTargetApp.processName.equals("system")) {
3480 Slog.d(TAG, "system process agent - spinning a thread");
3481 RestoreFileRunnable runner = new RestoreFileRunnable(
3482 mAgent, info, mPipes[0], token);
3483 new Thread(runner).start();
3484 } else {
3485 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3486 info.domain, info.path, info.mode, info.mtime,
3487 token, mBackupManagerBinder);
3488 }
Christopher Tate75a99702011-05-18 16:28:19 -07003489 }
3490 } catch (IOException e) {
3491 // couldn't dup the socket for a process-local restore
3492 Slog.d(TAG, "Couldn't establish restore");
3493 agentSuccess = false;
3494 okay = false;
3495 } catch (RemoteException e) {
Christopher Tate294b5122013-02-19 14:08:59 -08003496 // whoops, remote entity went away. We'll eat the content
Christopher Tate75a99702011-05-18 16:28:19 -07003497 // ourselves, then, and not copy it over.
3498 Slog.e(TAG, "Agent crashed during full restore");
3499 agentSuccess = false;
3500 okay = false;
3501 }
3502
3503 // Copy over the data if the agent is still good
3504 if (okay) {
3505 boolean pipeOkay = true;
3506 FileOutputStream pipe = new FileOutputStream(
3507 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003508 while (toCopy > 0) {
3509 int toRead = (toCopy > buffer.length)
3510 ? buffer.length : (int)toCopy;
3511 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003512 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003513 if (nRead <= 0) break;
3514 toCopy -= nRead;
3515
3516 // send it to the output pipe as long as things
3517 // are still good
3518 if (pipeOkay) {
3519 try {
3520 pipe.write(buffer, 0, nRead);
3521 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003522 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003523 pipeOkay = false;
3524 }
3525 }
3526 }
3527
3528 // done sending that file! Now we just need to consume
3529 // the delta from info.size to the end of block.
3530 skipTarPadding(info.size, instream);
3531
3532 // and now that we've sent it all, wait for the remote
3533 // side to acknowledge receipt
3534 agentSuccess = waitUntilOperationComplete(token);
3535 }
3536
3537 // okay, if the remote end failed at any point, deal with
3538 // it by ignoring the rest of the restore on it
3539 if (!agentSuccess) {
3540 mBackupHandler.removeMessages(MSG_TIMEOUT);
3541 tearDownPipes();
3542 tearDownAgent(mTargetApp);
3543 mAgent = null;
3544 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3545 }
3546 }
3547
3548 // Problems setting up the agent communication, or an already-
3549 // ignored package: skip to the next tar stream entry by
3550 // reading and discarding this file.
3551 if (!okay) {
3552 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3553 long bytesToConsume = (info.size + 511) & ~511;
3554 while (bytesToConsume > 0) {
3555 int toRead = (bytesToConsume > buffer.length)
3556 ? buffer.length : (int)bytesToConsume;
3557 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003558 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003559 if (nRead <= 0) break;
3560 bytesToConsume -= nRead;
3561 }
3562 }
3563 }
3564 }
3565 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003566 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003567 // treat as EOF
3568 info = null;
3569 }
3570
3571 return (info != null);
3572 }
3573
3574 void setUpPipes() throws IOException {
3575 mPipes = ParcelFileDescriptor.createPipe();
3576 }
3577
3578 void tearDownPipes() {
3579 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003580 try {
3581 mPipes[0].close();
3582 mPipes[0] = null;
3583 mPipes[1].close();
3584 mPipes[1] = null;
3585 } catch (IOException e) {
3586 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003587 }
3588 mPipes = null;
3589 }
3590 }
3591
3592 void tearDownAgent(ApplicationInfo app) {
3593 if (mAgent != null) {
3594 try {
3595 // unbind and tidy up even on timeout or failure, just in case
3596 mActivityManager.unbindBackupAgent(app);
3597
3598 // The agent was running with a stub Application object, so shut it down.
3599 // !!! We hardcode the confirmation UI's package name here rather than use a
3600 // manifest flag! TODO something less direct.
3601 if (app.uid != Process.SYSTEM_UID
3602 && !app.packageName.equals("com.android.backupconfirm")) {
3603 if (DEBUG) Slog.d(TAG, "Killing host process");
3604 mActivityManager.killApplicationProcess(app.processName, app.uid);
3605 } else {
3606 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3607 }
3608 } catch (RemoteException e) {
3609 Slog.d(TAG, "Lost app trying to shut down");
3610 }
3611 mAgent = null;
3612 }
3613 }
3614
3615 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3616 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003617 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003618 int mResult;
3619
3620 public void reset() {
3621 synchronized (mDone) {
3622 mDone.set(false);
3623 }
3624 }
3625
3626 public void waitForCompletion() {
3627 synchronized (mDone) {
3628 while (mDone.get() == false) {
3629 try {
3630 mDone.wait();
3631 } catch (InterruptedException e) { }
3632 }
3633 }
3634 }
3635
3636 int getResult() {
3637 return mResult;
3638 }
3639
3640 @Override
3641 public void packageInstalled(String packageName, int returnCode)
3642 throws RemoteException {
3643 synchronized (mDone) {
3644 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003645 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003646 mDone.set(true);
3647 mDone.notifyAll();
3648 }
3649 }
3650 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003651
3652 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3653 final AtomicBoolean mDone = new AtomicBoolean();
3654 int mResult;
3655
3656 public void reset() {
3657 synchronized (mDone) {
3658 mDone.set(false);
3659 }
3660 }
3661
3662 public void waitForCompletion() {
3663 synchronized (mDone) {
3664 while (mDone.get() == false) {
3665 try {
3666 mDone.wait();
3667 } catch (InterruptedException e) { }
3668 }
3669 }
3670 }
3671
3672 @Override
3673 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3674 synchronized (mDone) {
3675 mResult = returnCode;
3676 mDone.set(true);
3677 mDone.notifyAll();
3678 }
3679 }
3680 }
3681
Christopher Tate75a99702011-05-18 16:28:19 -07003682 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003683 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003684
3685 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3686 boolean okay = true;
3687
3688 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3689
3690 // The file content is an .apk file. Copy it out to a staging location and
3691 // attempt to install it.
3692 File apkFile = new File(mDataDir, info.packageName);
3693 try {
3694 FileOutputStream apkStream = new FileOutputStream(apkFile);
3695 byte[] buffer = new byte[32 * 1024];
3696 long size = info.size;
3697 while (size > 0) {
3698 long toRead = (buffer.length < size) ? buffer.length : size;
3699 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003700 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003701 apkStream.write(buffer, 0, didRead);
3702 size -= didRead;
3703 }
3704 apkStream.close();
3705
3706 // make sure the installer can read it
3707 apkFile.setReadable(true, false);
3708
3709 // Now install it
3710 Uri packageUri = Uri.fromFile(apkFile);
3711 mInstallObserver.reset();
3712 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003713 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3714 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003715 mInstallObserver.waitForCompletion();
3716
3717 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3718 // The only time we continue to accept install of data even if the
3719 // apk install failed is if we had already determined that we could
3720 // accept the data regardless.
3721 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3722 okay = false;
3723 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003724 } else {
3725 // Okay, the install succeeded. Make sure it was the right app.
3726 boolean uninstall = false;
3727 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3728 Slog.w(TAG, "Restore stream claimed to include apk for "
3729 + info.packageName + " but apk was really "
3730 + mInstallObserver.mPackageName);
3731 // delete the package we just put in place; it might be fraudulent
3732 okay = false;
3733 uninstall = true;
3734 } else {
3735 try {
3736 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3737 PackageManager.GET_SIGNATURES);
3738 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3739 Slog.w(TAG, "Restore stream contains apk of package "
3740 + info.packageName + " but it disallows backup/restore");
3741 okay = false;
3742 } else {
3743 // So far so good -- do the signatures match the manifest?
3744 Signature[] sigs = mManifestSignatures.get(info.packageName);
Christopher Tate2baf6dc2013-05-06 13:07:05 -07003745 if (signaturesMatch(sigs, pkg)) {
3746 // If this is a system-uid app without a declared backup agent,
3747 // don't restore any of the file data.
3748 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
3749 && (pkg.applicationInfo.backupAgentName == null)) {
3750 Slog.w(TAG, "Installed app " + info.packageName
3751 + " has restricted uid and no agent");
3752 okay = false;
3753 }
3754 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003755 Slog.w(TAG, "Installed app " + info.packageName
3756 + " signatures do not match restore manifest");
3757 okay = false;
3758 uninstall = true;
3759 }
3760 }
3761 } catch (NameNotFoundException e) {
3762 Slog.w(TAG, "Install of package " + info.packageName
3763 + " succeeded but now not found");
3764 okay = false;
3765 }
3766 }
3767
3768 // If we're not okay at this point, we need to delete the package
3769 // that we just installed.
3770 if (uninstall) {
3771 mDeleteObserver.reset();
3772 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3773 mDeleteObserver, 0);
3774 mDeleteObserver.waitForCompletion();
3775 }
Christopher Tate75a99702011-05-18 16:28:19 -07003776 }
3777 } catch (IOException e) {
3778 Slog.e(TAG, "Unable to transcribe restored apk for install");
3779 okay = false;
3780 } finally {
3781 apkFile.delete();
3782 }
3783
3784 return okay;
3785 }
3786
3787 // Given an actual file content size, consume the post-content padding mandated
3788 // by the tar format.
3789 void skipTarPadding(long size, InputStream instream) throws IOException {
3790 long partial = (size + 512) % 512;
3791 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003792 final int needed = 512 - (int)partial;
3793 byte[] buffer = new byte[needed];
3794 if (readExactly(instream, buffer, 0, needed) == needed) {
3795 mBytes += needed;
3796 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003797 }
3798 }
3799
3800 // Returns a policy constant; takes a buffer arg to reduce memory churn
3801 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3802 throws IOException {
3803 // Fail on suspiciously large manifest files
3804 if (info.size > 64 * 1024) {
3805 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3806 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003807
Christopher Tate75a99702011-05-18 16:28:19 -07003808 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003809 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3810 mBytes += info.size;
3811 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003812
3813 RestorePolicy policy = RestorePolicy.IGNORE;
3814 String[] str = new String[1];
3815 int offset = 0;
3816
3817 try {
3818 offset = extractLine(buffer, offset, str);
3819 int version = Integer.parseInt(str[0]);
3820 if (version == BACKUP_MANIFEST_VERSION) {
3821 offset = extractLine(buffer, offset, str);
3822 String manifestPackage = str[0];
3823 // TODO: handle <original-package>
3824 if (manifestPackage.equals(info.packageName)) {
3825 offset = extractLine(buffer, offset, str);
3826 version = Integer.parseInt(str[0]); // app version
3827 offset = extractLine(buffer, offset, str);
3828 int platformVersion = Integer.parseInt(str[0]);
3829 offset = extractLine(buffer, offset, str);
3830 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3831 offset = extractLine(buffer, offset, str);
3832 boolean hasApk = str[0].equals("1");
3833 offset = extractLine(buffer, offset, str);
3834 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003835 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003836 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003837 for (int i = 0; i < numSigs; i++) {
3838 offset = extractLine(buffer, offset, str);
3839 sigs[i] = new Signature(str[0]);
3840 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003841 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003842
3843 // Okay, got the manifest info we need...
3844 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003845 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3846 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003847 // Fall through to IGNORE if the app explicitly disallows backup
3848 final int flags = pkgInfo.applicationInfo.flags;
3849 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003850 // Restore system-uid-space packages only if they have
3851 // defined a custom backup agent
3852 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3853 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3854 // Verify signatures against any installed version; if they
3855 // don't match, then we fall though and ignore the data. The
3856 // signatureMatch() method explicitly ignores the signature
3857 // check for packages installed on the system partition, because
3858 // such packages are signed with the platform cert instead of
3859 // the app developer's cert, so they're different on every
3860 // device.
3861 if (signaturesMatch(sigs, pkgInfo)) {
3862 if (pkgInfo.versionCode >= version) {
3863 Slog.i(TAG, "Sig + version match; taking data");
3864 policy = RestorePolicy.ACCEPT;
3865 } else {
3866 // The data is from a newer version of the app than
3867 // is presently installed. That means we can only
3868 // use it if the matching apk is also supplied.
3869 Slog.d(TAG, "Data version " + version
3870 + " is newer than installed version "
3871 + pkgInfo.versionCode + " - requiring apk");
3872 policy = RestorePolicy.ACCEPT_IF_APK;
3873 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003874 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003875 Slog.w(TAG, "Restore manifest signatures do not match "
3876 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003877 }
Christopher Tate75a99702011-05-18 16:28:19 -07003878 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003879 Slog.w(TAG, "Package " + info.packageName
3880 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003881 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003882 } else {
3883 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3884 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003885 }
3886 } catch (NameNotFoundException e) {
3887 // Okay, the target app isn't installed. We can process
3888 // the restore properly only if the dataset provides the
3889 // apk file and we can successfully install it.
3890 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3891 + " not installed; requiring apk in dataset");
3892 policy = RestorePolicy.ACCEPT_IF_APK;
3893 }
3894
3895 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3896 Slog.i(TAG, "Cannot restore package " + info.packageName
3897 + " without the matching .apk");
3898 }
3899 } else {
3900 Slog.i(TAG, "Missing signature on backed-up package "
3901 + info.packageName);
3902 }
3903 } else {
3904 Slog.i(TAG, "Expected package " + info.packageName
3905 + " but restore manifest claims " + manifestPackage);
3906 }
3907 } else {
3908 Slog.i(TAG, "Unknown restore manifest version " + version
3909 + " for package " + info.packageName);
3910 }
3911 } catch (NumberFormatException e) {
3912 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003913 } catch (IllegalArgumentException e) {
3914 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003915 }
3916
3917 return policy;
3918 }
3919
3920 // Builds a line from a byte buffer starting at 'offset', and returns
3921 // the index of the next unconsumed data in the buffer.
3922 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3923 final int end = buffer.length;
3924 if (offset >= end) throw new IOException("Incomplete data");
3925
3926 int pos;
3927 for (pos = offset; pos < end; pos++) {
3928 byte c = buffer[pos];
3929 // at LF we declare end of line, and return the next char as the
3930 // starting point for the next time through
3931 if (c == '\n') {
3932 break;
3933 }
3934 }
3935 outStr[0] = new String(buffer, offset, pos - offset);
3936 pos++; // may be pointing an extra byte past the end but that's okay
3937 return pos;
3938 }
3939
3940 void dumpFileMetadata(FileMetadata info) {
3941 if (DEBUG) {
3942 StringBuilder b = new StringBuilder(128);
3943
3944 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003945 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003946 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3947 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3948 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3949 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3950 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3951 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3952 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3953 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3954 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3955 b.append(String.format(" %9d ", info.size));
3956
3957 Date stamp = new Date(info.mtime);
Elliott Hughes64a277d82013-03-18 17:47:22 -07003958 b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
Christopher Tate75a99702011-05-18 16:28:19 -07003959
3960 b.append(info.packageName);
3961 b.append(" :: ");
3962 b.append(info.domain);
3963 b.append(" :: ");
3964 b.append(info.path);
3965
3966 Slog.i(TAG, b.toString());
3967 }
3968 }
3969 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3970 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3971 byte[] block = new byte[512];
3972 FileMetadata info = null;
3973
3974 boolean gotHeader = readTarHeader(instream, block);
3975 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003976 try {
3977 // okay, presume we're okay, and extract the various metadata
3978 info = new FileMetadata();
3979 info.size = extractRadix(block, 124, 12, 8);
3980 info.mtime = extractRadix(block, 136, 12, 8);
3981 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003982
Christopher Tate2efd2db2011-07-19 16:32:49 -07003983 info.path = extractString(block, 345, 155); // prefix
3984 String path = extractString(block, 0, 100);
3985 if (path.length() > 0) {
3986 if (info.path.length() > 0) info.path += '/';
3987 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003988 }
Christopher Tate75a99702011-05-18 16:28:19 -07003989
Christopher Tate2efd2db2011-07-19 16:32:49 -07003990 // tar link indicator field: 1 byte at offset 156 in the header.
3991 int typeChar = block[156];
3992 if (typeChar == 'x') {
3993 // pax extended header, so we need to read that
3994 gotHeader = readPaxExtendedHeader(instream, info);
3995 if (gotHeader) {
3996 // and after a pax extended header comes another real header -- read
3997 // that to find the real file type
3998 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003999 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004000 if (!gotHeader) throw new IOException("Bad or missing pax header");
4001
4002 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07004003 }
Christopher Tate75a99702011-05-18 16:28:19 -07004004
Christopher Tate2efd2db2011-07-19 16:32:49 -07004005 switch (typeChar) {
4006 case '0': info.type = BackupAgent.TYPE_FILE; break;
4007 case '5': {
4008 info.type = BackupAgent.TYPE_DIRECTORY;
4009 if (info.size != 0) {
4010 Slog.w(TAG, "Directory entry with nonzero size in header");
4011 info.size = 0;
4012 }
4013 break;
Christopher Tate75a99702011-05-18 16:28:19 -07004014 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004015 case 0: {
4016 // presume EOF
4017 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
4018 return null;
4019 }
4020 default: {
4021 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
4022 throw new IOException("Unknown entity type " + typeChar);
4023 }
Christopher Tate75a99702011-05-18 16:28:19 -07004024 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004025
4026 // Parse out the path
4027 //
4028 // first: apps/shared/unrecognized
4029 if (FullBackup.SHARED_PREFIX.regionMatches(0,
4030 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4031 // File in shared storage. !!! TODO: implement this.
4032 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08004033 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004034 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4035 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4036 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4037 info.path, 0, FullBackup.APPS_PREFIX.length())) {
4038 // App content! Parse out the package name and domain
4039
4040 // strip the apps/ prefix
4041 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4042
4043 // extract the package name
4044 int slash = info.path.indexOf('/');
4045 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4046 info.packageName = info.path.substring(0, slash);
4047 info.path = info.path.substring(slash+1);
4048
4049 // if it's a manifest we're done, otherwise parse out the domains
4050 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4051 slash = info.path.indexOf('/');
4052 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4053 info.domain = info.path.substring(0, slash);
Christopher Tate2efd2db2011-07-19 16:32:49 -07004054 info.path = info.path.substring(slash + 1);
4055 }
4056 }
4057 } catch (IOException e) {
4058 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07004059 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07004060 HEXLOG(block);
4061 }
4062 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07004063 }
4064 }
4065 return info;
4066 }
4067
Christopher Tate2efd2db2011-07-19 16:32:49 -07004068 private void HEXLOG(byte[] block) {
4069 int offset = 0;
4070 int todo = block.length;
4071 StringBuilder buf = new StringBuilder(64);
4072 while (todo > 0) {
4073 buf.append(String.format("%04x ", offset));
4074 int numThisLine = (todo > 16) ? 16 : todo;
4075 for (int i = 0; i < numThisLine; i++) {
4076 buf.append(String.format("%02x ", block[offset+i]));
4077 }
4078 Slog.i("hexdump", buf.toString());
4079 buf.setLength(0);
4080 todo -= numThisLine;
4081 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07004082 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07004083 }
4084
Christopher Tate6853fcf2011-08-10 17:52:21 -07004085 // Read exactly the given number of bytes into a buffer at the stated offset.
4086 // Returns false if EOF is encountered before the requested number of bytes
4087 // could be read.
4088 int readExactly(InputStream in, byte[] buffer, int offset, int size)
4089 throws IOException {
4090 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4091
4092 int soFar = 0;
4093 while (soFar < size) {
4094 int nRead = in.read(buffer, offset + soFar, size - soFar);
4095 if (nRead <= 0) {
4096 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4097 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004098 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004099 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004100 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004101 return soFar;
4102 }
4103
4104 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4105 final int got = readExactly(instream, block, 0, 512);
4106 if (got == 0) return false; // Clean EOF
4107 if (got < 512) throw new IOException("Unable to read full block header");
4108 mBytes += 512;
4109 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07004110 }
4111
4112 // overwrites 'info' fields based on the pax extended header
4113 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4114 throws IOException {
4115 // We should never see a pax extended header larger than this
4116 if (info.size > 32*1024) {
4117 Slog.w(TAG, "Suspiciously large pax header size " + info.size
4118 + " - aborting");
4119 throw new IOException("Sanity failure: pax header size " + info.size);
4120 }
4121
4122 // read whole blocks, not just the content size
4123 int numBlocks = (int)((info.size + 511) >> 9);
4124 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07004125 if (readExactly(instream, data, 0, data.length) < data.length) {
4126 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07004127 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07004128 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07004129
4130 final int contentSize = (int) info.size;
4131 int offset = 0;
4132 do {
4133 // extract the line at 'offset'
4134 int eol = offset+1;
4135 while (eol < contentSize && data[eol] != ' ') eol++;
4136 if (eol >= contentSize) {
4137 // error: we just hit EOD looking for the end of the size field
4138 throw new IOException("Invalid pax data");
4139 }
4140 // eol points to the space between the count and the key
4141 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4142 int key = eol + 1; // start of key=value
4143 eol = offset + linelen - 1; // trailing LF
4144 int value;
4145 for (value = key+1; data[value] != '=' && value <= eol; value++);
4146 if (value > eol) {
4147 throw new IOException("Invalid pax declaration");
4148 }
4149
4150 // pax requires that key/value strings be in UTF-8
4151 String keyStr = new String(data, key, value-key, "UTF-8");
4152 // -1 to strip the trailing LF
4153 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4154
4155 if ("path".equals(keyStr)) {
4156 info.path = valStr;
4157 } else if ("size".equals(keyStr)) {
4158 info.size = Long.parseLong(valStr);
4159 } else {
4160 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4161 }
4162
4163 offset += linelen;
4164 } while (offset < contentSize);
4165
4166 return true;
4167 }
4168
4169 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4170 throws IOException {
4171 long value = 0;
4172 final int end = offset + maxChars;
4173 for (int i = offset; i < end; i++) {
4174 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004175 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004176 if (b == 0 || b == ' ') break;
4177 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004178 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004179 }
4180 value = radix * value + (b - '0');
4181 }
4182 return value;
4183 }
4184
4185 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4186 final int end = offset + maxChars;
4187 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004188 // tar string fields terminate early with a NUL
4189 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004190 return new String(data, offset, eos-offset, "US-ASCII");
4191 }
4192
4193 void sendStartRestore() {
4194 if (mObserver != null) {
4195 try {
4196 mObserver.onStartRestore();
4197 } catch (RemoteException e) {
4198 Slog.w(TAG, "full restore observer went away: startRestore");
4199 mObserver = null;
4200 }
4201 }
4202 }
4203
4204 void sendOnRestorePackage(String name) {
4205 if (mObserver != null) {
4206 try {
4207 // TODO: use a more user-friendly name string
4208 mObserver.onRestorePackage(name);
4209 } catch (RemoteException e) {
4210 Slog.w(TAG, "full restore observer went away: restorePackage");
4211 mObserver = null;
4212 }
4213 }
4214 }
4215
4216 void sendEndRestore() {
4217 if (mObserver != null) {
4218 try {
4219 mObserver.onEndRestore();
4220 } catch (RemoteException e) {
4221 Slog.w(TAG, "full restore observer went away: endRestore");
4222 mObserver = null;
4223 }
4224 }
4225 }
4226 }
4227
Christopher Tatedf01dea2009-06-09 20:45:02 -07004228 // ----- Restore handling -----
4229
Christopher Tate78dd4a72009-11-04 11:49:08 -08004230 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4231 // If the target resides on the system partition, we allow it to restore
4232 // data from the like-named package in a restore set even if the signatures
4233 // do not match. (Unlike general applications, those flashed to the system
4234 // partition will be signed with the device's platform certificate, so on
4235 // different phones the same system app will have different signatures.)
4236 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004237 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004238 return true;
4239 }
4240
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004241 // Allow unsigned apps, but not signed on one device and unsigned on the other
4242 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004243 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004244 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004245 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004246 if ((storedSigs == null || storedSigs.length == 0)
4247 && (deviceSigs == null || deviceSigs.length == 0)) {
4248 return true;
4249 }
4250 if (storedSigs == null || deviceSigs == null) {
4251 return false;
4252 }
4253
Christopher Tateabce4e82009-06-18 18:35:32 -07004254 // !!! TODO: this demands that every stored signature match one
4255 // that is present on device, and does not demand the converse.
4256 // Is this this right policy?
4257 int nStored = storedSigs.length;
4258 int nDevice = deviceSigs.length;
4259
4260 for (int i=0; i < nStored; i++) {
4261 boolean match = false;
4262 for (int j=0; j < nDevice; j++) {
4263 if (storedSigs[i].equals(deviceSigs[j])) {
4264 match = true;
4265 break;
4266 }
4267 }
4268 if (!match) {
4269 return false;
4270 }
4271 }
4272 return true;
4273 }
4274
Christopher Tate2982d062011-09-06 20:35:24 -07004275 enum RestoreState {
4276 INITIAL,
4277 DOWNLOAD_DATA,
4278 PM_METADATA,
4279 RUNNING_QUEUE,
4280 FINAL
4281 }
4282
4283 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004284 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004285 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004286 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004287 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004288 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004289 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004290 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004291 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004292 private long mStartRealtime;
4293 private PackageManagerBackupAgent mPmAgent;
4294 private List<PackageInfo> mAgentPackages;
4295 private ArrayList<PackageInfo> mRestorePackages;
4296 private RestoreState mCurrentState;
4297 private int mCount;
4298 private boolean mFinished;
4299 private int mStatus;
4300 private File mBackupDataName;
4301 private File mNewStateName;
4302 private File mSavedStateName;
4303 private ParcelFileDescriptor mBackupData;
4304 private ParcelFileDescriptor mNewState;
4305 private PackageInfo mCurrentPackage;
4306
Christopher Tatedf01dea2009-06-09 20:45:02 -07004307
Christopher Tate5cbbf562009-06-22 16:44:51 -07004308 class RestoreRequest {
4309 public PackageInfo app;
4310 public int storedAppVersion;
4311
4312 RestoreRequest(PackageInfo _app, int _version) {
4313 app = _app;
4314 storedAppVersion = _version;
4315 }
4316 }
4317
Christopher Tate44a27902010-01-27 17:15:49 -08004318 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004319 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004320 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004321 mCurrentState = RestoreState.INITIAL;
4322 mFinished = false;
4323 mPmAgent = null;
4324
Christopher Tatedf01dea2009-06-09 20:45:02 -07004325 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004326 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004327 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004328 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004329 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004330 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004331
Christopher Tate284f1bb2011-07-07 14:31:18 -07004332 if (filterSet != null) {
4333 mFilterSet = new HashSet<String>();
4334 for (String pkg : filterSet) {
4335 mFilterSet.add(pkg);
4336 }
4337 } else {
4338 mFilterSet = null;
4339 }
4340
Christopher Tate5cb400b2009-06-25 16:03:14 -07004341 try {
4342 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4343 } catch (RemoteException e) {
4344 // can't happen; the transport is local
4345 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004346 }
4347
Christopher Tate2982d062011-09-06 20:35:24 -07004348 // Execute one tick of whatever state machine the task implements
4349 @Override
4350 public void execute() {
4351 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4352 switch (mCurrentState) {
4353 case INITIAL:
4354 beginRestore();
4355 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004356
Christopher Tate2982d062011-09-06 20:35:24 -07004357 case DOWNLOAD_DATA:
4358 downloadRestoreData();
4359 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004360
Christopher Tate2982d062011-09-06 20:35:24 -07004361 case PM_METADATA:
4362 restorePmMetadata();
4363 break;
4364
4365 case RUNNING_QUEUE:
4366 restoreNextAgent();
4367 break;
4368
4369 case FINAL:
4370 if (!mFinished) finalizeRestore();
4371 else {
4372 Slog.e(TAG, "Duplicate finish");
4373 }
4374 mFinished = true;
4375 break;
4376 }
4377 }
4378
4379 // Initialize and set up for the PM metadata restore, which comes first
4380 void beginRestore() {
4381 // Don't account time doing the restore as inactivity of the app
4382 // that has opened a restore session.
4383 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4384
4385 // Assume error until we successfully init everything
4386 mStatus = BackupConstants.TRANSPORT_ERROR;
4387
Christopher Tatedf01dea2009-06-09 20:45:02 -07004388 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004389 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004390 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004391
Dan Egnorefe52642009-06-24 00:16:33 -07004392 // Get the list of all packages which have backup enabled.
4393 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004394 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004395 PackageInfo omPackage = new PackageInfo();
4396 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004397 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004398
Christopher Tate2982d062011-09-06 20:35:24 -07004399 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004400 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004401 // if there's a filter set, strip out anything that isn't
4402 // present before proceeding
4403 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004404 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4405 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004406 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004407 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004408 }
4409 }
Christopher Tate2982d062011-09-06 20:35:24 -07004410 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004411 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004412 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004413 Slog.i(TAG, " " + p);
4414 }
4415 }
4416 }
Christopher Tate2982d062011-09-06 20:35:24 -07004417 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004418 } else {
4419 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004420 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004421 }
Dan Egnorefe52642009-06-24 00:16:33 -07004422
Christopher Tate7d562ec2009-06-25 18:03:43 -07004423 // let the observer know that we're running
4424 if (mObserver != null) {
4425 try {
4426 // !!! TODO: get an actual count from the transport after
4427 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004428 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004429 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004430 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004431 mObserver = null;
4432 }
4433 }
Christopher Tate2982d062011-09-06 20:35:24 -07004434 } catch (RemoteException e) {
4435 // Something has gone catastrophically wrong with the transport
4436 Slog.e(TAG, "Error communicating with transport for restore");
4437 executeNextState(RestoreState.FINAL);
4438 return;
4439 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004440
Christopher Tate2982d062011-09-06 20:35:24 -07004441 mStatus = BackupConstants.TRANSPORT_OK;
4442 executeNextState(RestoreState.DOWNLOAD_DATA);
4443 }
4444
4445 void downloadRestoreData() {
4446 // Note that the download phase can be very time consuming, but we're executing
4447 // it inline here on the looper. This is "okay" because it is not calling out to
4448 // third party code; the transport is "trusted," and so we assume it is being a
4449 // good citizen and timing out etc when appropriate.
4450 //
4451 // TODO: when appropriate, move the download off the looper and rearrange the
4452 // error handling around that.
4453 try {
4454 mStatus = mTransport.startRestore(mToken,
4455 mRestorePackages.toArray(new PackageInfo[0]));
4456 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004457 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004458 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004459 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004460 return;
4461 }
Christopher Tate2982d062011-09-06 20:35:24 -07004462 } catch (RemoteException e) {
4463 Slog.e(TAG, "Error communicating with transport for restore");
4464 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4465 mStatus = BackupConstants.TRANSPORT_ERROR;
4466 executeNextState(RestoreState.FINAL);
4467 return;
4468 }
Dan Egnorefe52642009-06-24 00:16:33 -07004469
Christopher Tate2982d062011-09-06 20:35:24 -07004470 // Successful download of the data to be parceled out to the apps, so off we go.
4471 executeNextState(RestoreState.PM_METADATA);
4472 }
4473
4474 void restorePmMetadata() {
4475 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004476 String packageName = mTransport.nextRestorePackage();
4477 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004478 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004479 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004480 mStatus = BackupConstants.TRANSPORT_ERROR;
4481 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004482 return;
4483 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004484 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004485 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004486 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004487 mStatus = BackupConstants.TRANSPORT_OK;
4488 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004489 return;
4490 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004491 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004492 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004493 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004494 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004495 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004496 return;
4497 }
4498
4499 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004500 PackageInfo omPackage = new PackageInfo();
4501 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4502 mPmAgent = new PackageManagerBackupAgent(
4503 mPackageManager, mAgentPackages);
4504 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004505 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004506 // The PM agent called operationComplete() already, because our invocation
4507 // of it is process-local and therefore synchronous. That means that a
4508 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4509 // proceed with running the queue do we remove that pending message and
4510 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004511
Christopher Tate8c032472009-07-02 14:28:47 -07004512 // Verify that the backup set includes metadata. If not, we can't do
4513 // signature/version verification etc, so we simply do not proceed with
4514 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004515 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004516 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004517 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004518 "Package manager restore metadata missing");
4519 mStatus = BackupConstants.TRANSPORT_ERROR;
4520 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4521 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004522 return;
4523 }
Christopher Tate2982d062011-09-06 20:35:24 -07004524 } catch (RemoteException e) {
4525 Slog.e(TAG, "Error communicating with transport for restore");
4526 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4527 mStatus = BackupConstants.TRANSPORT_ERROR;
4528 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4529 executeNextState(RestoreState.FINAL);
4530 return;
4531 }
Christopher Tate8c032472009-07-02 14:28:47 -07004532
Christopher Tate2982d062011-09-06 20:35:24 -07004533 // Metadata is intact, so we can now run the restore queue. If we get here,
4534 // we have already enqueued the necessary next-step message on the looper.
4535 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004536
Christopher Tate2982d062011-09-06 20:35:24 -07004537 void restoreNextAgent() {
4538 try {
4539 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004540
Christopher Tate2982d062011-09-06 20:35:24 -07004541 if (packageName == null) {
4542 Slog.e(TAG, "Error getting next restore package");
4543 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4544 executeNextState(RestoreState.FINAL);
4545 return;
4546 } else if (packageName.equals("")) {
4547 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4548 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4549 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4550 executeNextState(RestoreState.FINAL);
4551 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004552 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004553
4554 if (mObserver != null) {
4555 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004556 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004557 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004558 Slog.d(TAG, "Restore observer died in onUpdate");
4559 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004560 }
4561 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004562
Christopher Tate2982d062011-09-06 20:35:24 -07004563 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4564 if (metaInfo == null) {
4565 Slog.e(TAG, "Missing metadata for " + packageName);
4566 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4567 "Package metadata missing");
4568 executeNextState(RestoreState.RUNNING_QUEUE);
4569 return;
Christopher Tate84725812010-02-04 15:52:40 -08004570 }
4571
Christopher Tate2982d062011-09-06 20:35:24 -07004572 PackageInfo packageInfo;
4573 try {
4574 int flags = PackageManager.GET_SIGNATURES;
4575 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4576 } catch (NameNotFoundException e) {
4577 Slog.e(TAG, "Invalid package restoring data", e);
4578 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4579 "Package missing on device");
4580 executeNextState(RestoreState.RUNNING_QUEUE);
4581 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004582 }
4583
Christopher Tatee7287a02012-09-07 18:32:12 -07004584 if (packageInfo.applicationInfo.backupAgentName == null
4585 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4586 if (DEBUG) {
4587 Slog.i(TAG, "Data exists for package " + packageName
4588 + " but app has no agent; skipping");
4589 }
4590 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4591 "Package has no agent");
4592 executeNextState(RestoreState.RUNNING_QUEUE);
4593 return;
4594 }
4595
Christopher Tate2982d062011-09-06 20:35:24 -07004596 if (metaInfo.versionCode > packageInfo.versionCode) {
4597 // Data is from a "newer" version of the app than we have currently
4598 // installed. If the app has not declared that it is prepared to
4599 // handle this case, we do not attempt the restore.
4600 if ((packageInfo.applicationInfo.flags
4601 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4602 String message = "Version " + metaInfo.versionCode
4603 + " > installed version " + packageInfo.versionCode;
4604 Slog.w(TAG, "Package " + packageName + ": " + message);
4605 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4606 packageName, message);
4607 executeNextState(RestoreState.RUNNING_QUEUE);
4608 return;
4609 } else {
4610 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4611 + " > installed " + packageInfo.versionCode
4612 + " but restoreAnyVersion");
4613 }
4614 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004615
Christopher Tate2982d062011-09-06 20:35:24 -07004616 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4617 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4618 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4619 "Signature mismatch");
4620 executeNextState(RestoreState.RUNNING_QUEUE);
4621 return;
4622 }
4623
4624 if (DEBUG) Slog.v(TAG, "Package " + packageName
4625 + " restore version [" + metaInfo.versionCode
4626 + "] is compatible with installed version ["
4627 + packageInfo.versionCode + "]");
4628
4629 // Then set up and bind the agent
4630 IBackupAgent agent = bindToAgentSynchronous(
4631 packageInfo.applicationInfo,
4632 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4633 if (agent == null) {
4634 Slog.w(TAG, "Can't find backup agent for " + packageName);
4635 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4636 "Restore agent missing");
4637 executeNextState(RestoreState.RUNNING_QUEUE);
4638 return;
4639 }
4640
4641 // And then finally start the restore on this agent
4642 try {
4643 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4644 ++mCount;
4645 } catch (Exception e) {
4646 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4647 agentErrorCleanup();
4648 executeNextState(RestoreState.RUNNING_QUEUE);
4649 }
4650 } catch (RemoteException e) {
4651 Slog.e(TAG, "Unable to fetch restore data from transport");
4652 mStatus = BackupConstants.TRANSPORT_ERROR;
4653 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004654 }
4655 }
4656
Christopher Tate2982d062011-09-06 20:35:24 -07004657 void finalizeRestore() {
4658 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4659
4660 try {
4661 mTransport.finishRestore();
4662 } catch (RemoteException e) {
4663 Slog.e(TAG, "Error finishing restore", e);
4664 }
4665
4666 if (mObserver != null) {
4667 try {
4668 mObserver.restoreFinished(mStatus);
4669 } catch (RemoteException e) {
4670 Slog.d(TAG, "Restore observer died at restoreFinished");
4671 }
4672 }
4673
4674 // If this was a restoreAll operation, record that this was our
4675 // ancestral dataset, as well as the set of apps that are possibly
4676 // restoreable from the dataset
4677 if (mTargetPackage == null && mPmAgent != null) {
4678 mAncestralPackages = mPmAgent.getRestoredPackages();
4679 mAncestralToken = mToken;
4680 writeRestoreTokens();
4681 }
4682
4683 // We must under all circumstances tell the Package Manager to
4684 // proceed with install notifications if it's waiting for us.
4685 if (mPmToken > 0) {
4686 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4687 try {
4688 mPackageManagerBinder.finishPackageInstall(mPmToken);
4689 } catch (RemoteException e) { /* can't happen */ }
4690 }
4691
4692 // Furthermore we need to reset the session timeout clock
4693 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4694 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4695 TIMEOUT_RESTORE_INTERVAL);
4696
4697 // done; we can finally release the wakelock
4698 Slog.i(TAG, "Restore complete.");
4699 mWakelock.release();
4700 }
4701
4702 // Call asynchronously into the app, passing it the restore data. The next step
4703 // after this is always a callback, either operationComplete() or handleTimeout().
4704 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004705 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004706 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004707 final String packageName = app.packageName;
4708
Christopher Tate2982d062011-09-06 20:35:24 -07004709 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004710
Christopher Tatec7b31e32009-06-10 15:49:30 -07004711 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004712 mBackupDataName = new File(mDataDir, packageName + ".restore");
4713 mNewStateName = new File(mStateDir, packageName + ".new");
4714 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004715
Christopher Tate4a627c72011-04-01 14:43:32 -07004716 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004717 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004718 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004719 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004720 ParcelFileDescriptor.MODE_READ_WRITE |
4721 ParcelFileDescriptor.MODE_CREATE |
4722 ParcelFileDescriptor.MODE_TRUNCATE);
4723
rpcraigebab0ae2012-12-04 09:37:23 -05004724 if (!SELinux.restorecon(mBackupDataName)) {
4725 Slog.e(TAG, "SElinux restorecon failed for " + mBackupDataName);
4726 }
4727
Christopher Tate2982d062011-09-06 20:35:24 -07004728 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004729 // Transport-level failure, so we wind everything up and
4730 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004731 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004732 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004733 mBackupData.close();
4734 mBackupDataName.delete();
4735 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004736 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004737 }
4738
4739 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004740 mBackupData.close();
4741 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004742 ParcelFileDescriptor.MODE_READ_ONLY);
4743
Christopher Tate2982d062011-09-06 20:35:24 -07004744 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004745 ParcelFileDescriptor.MODE_READ_WRITE |
4746 ParcelFileDescriptor.MODE_CREATE |
4747 ParcelFileDescriptor.MODE_TRUNCATE);
4748
Christopher Tate44a27902010-01-27 17:15:49 -08004749 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004750 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4751 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004752 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004753 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004754 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004755 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004756
Christopher Tate2982d062011-09-06 20:35:24 -07004757 // After a restore failure we go back to running the queue. If there
4758 // are no more packages to be restored that will be handled by the
4759 // next step.
4760 executeNextState(RestoreState.RUNNING_QUEUE);
4761 }
4762 }
Chris Tate249345b2010-10-29 12:57:04 -07004763
Christopher Tate2982d062011-09-06 20:35:24 -07004764 void agentErrorCleanup() {
4765 // If the agent fails restore, it might have put the app's data
4766 // into an incoherent state. For consistency we wipe its data
4767 // again in this case before continuing with normal teardown
4768 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4769 agentCleanup();
4770 }
4771
4772 void agentCleanup() {
4773 mBackupDataName.delete();
4774 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4775 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4776 mBackupData = mNewState = null;
4777
4778 // if everything went okay, remember the recorded state now
4779 //
4780 // !!! TODO: the restored data should be migrated on the server
4781 // side into the current dataset. In that case the new state file
4782 // we just created would reflect the data already extant in the
4783 // backend, so there'd be nothing more to do. Until that happens,
4784 // however, we need to make sure that we record the data to the
4785 // current backend dataset. (Yes, this means shipping the data over
4786 // the wire in both directions. That's bad, but consistency comes
4787 // first, then efficiency.) Once we introduce server-side data
4788 // migration to the newly-restored device's dataset, we will change
4789 // the following from a discard of the newly-written state to the
4790 // "correct" operation of renaming into the canonical state blob.
4791 mNewStateName.delete(); // TODO: remove; see above comment
4792 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4793
4794 // If this wasn't the PM pseudopackage, tear down the agent side
4795 if (mCurrentPackage.applicationInfo != null) {
4796 // unbind and tidy up even on timeout or failure
4797 try {
4798 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4799
4800 // The agent was probably running with a stub Application object,
4801 // which isn't a valid run mode for the main app logic. Shut
4802 // down the app so that next time it's launched, it gets the
4803 // usual full initialization. Note that this is only done for
4804 // full-system restores: when a single app has requested a restore,
4805 // it is explicitly not killed following that operation.
4806 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4807 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4808 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4809 + mCurrentPackage.applicationInfo.processName);
4810 mActivityManager.killApplicationProcess(
4811 mCurrentPackage.applicationInfo.processName,
4812 mCurrentPackage.applicationInfo.uid);
4813 }
4814 } catch (RemoteException e) {
4815 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004816 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004817 }
Christopher Tate2982d062011-09-06 20:35:24 -07004818
4819 // The caller is responsible for reestablishing the state machine; our
4820 // responsibility here is to clear the decks for whatever comes next.
4821 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4822 synchronized (mCurrentOpLock) {
4823 mCurrentOperations.clear();
4824 }
4825 }
4826
4827 // A call to agent.doRestore() has been positively acknowledged as complete
4828 @Override
4829 public void operationComplete() {
4830 int size = (int) mBackupDataName.length();
4831 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4832 // Just go back to running the restore queue
4833 agentCleanup();
4834
4835 executeNextState(RestoreState.RUNNING_QUEUE);
4836 }
4837
4838 // A call to agent.doRestore() has timed out
4839 @Override
4840 public void handleTimeout() {
4841 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4842 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4843 mCurrentPackage.packageName, "restore timeout");
4844 // Handle like an agent that threw on invocation: wipe it and go on to the next
4845 agentErrorCleanup();
4846 executeNextState(RestoreState.RUNNING_QUEUE);
4847 }
4848
4849 void executeNextState(RestoreState nextState) {
4850 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4851 + this + " nextState=" + nextState);
4852 mCurrentState = nextState;
4853 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4854 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004855 }
4856 }
4857
Christopher Tate44a27902010-01-27 17:15:49 -08004858 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004859 IBackupTransport mTransport;
4860 PackageInfo mPackage;
4861
Christopher Tate44a27902010-01-27 17:15:49 -08004862 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004863 mTransport = transport;
4864 mPackage = packageInfo;
4865 }
4866
Christopher Tateee0e78a2009-07-02 11:17:03 -07004867 public void run() {
4868 try {
4869 // Clear the on-device backup state to ensure a full backup next time
4870 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4871 File stateFile = new File(stateDir, mPackage.packageName);
4872 stateFile.delete();
4873
4874 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004875 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004876 mTransport.clearBackupData(mPackage);
4877 } catch (RemoteException e) {
4878 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004879 } catch (Exception e) {
4880 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004881 } finally {
4882 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004883 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004884 mTransport.finishBackup();
4885 } catch (RemoteException e) {
4886 // can't happen; the transport is local
4887 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004888
4889 // Last but not least, release the cpu
4890 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004891 }
4892 }
4893 }
4894
Christopher Tate44a27902010-01-27 17:15:49 -08004895 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004896 HashSet<String> mQueue;
4897
Christopher Tate44a27902010-01-27 17:15:49 -08004898 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004899 mQueue = transportNames;
4900 }
4901
Christopher Tate4cc86e12009-09-21 19:36:51 -07004902 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004903 try {
4904 for (String transportName : mQueue) {
4905 IBackupTransport transport = getTransport(transportName);
4906 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004907 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004908 continue;
4909 }
4910
Joe Onorato8a9b2202010-02-26 18:56:32 -08004911 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004912 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004913 long startRealtime = SystemClock.elapsedRealtime();
4914 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004915
Christopher Tate4cc86e12009-09-21 19:36:51 -07004916 if (status == BackupConstants.TRANSPORT_OK) {
4917 status = transport.finishBackup();
4918 }
4919
4920 // Okay, the wipe really happened. Clean up our local bookkeeping.
4921 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004922 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004923 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004924 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004925 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004926 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004927 synchronized (mQueueLock) {
4928 recordInitPendingLocked(false, transportName);
4929 }
Dan Egnor726247c2009-09-29 19:12:31 -07004930 } else {
4931 // If this didn't work, requeue this one and try again
4932 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004933 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004934 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004935 synchronized (mQueueLock) {
4936 recordInitPendingLocked(true, transportName);
4937 }
4938 // do this via another alarm to make sure of the wakelock states
4939 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004940 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004941 + transportName + " resched in " + delay);
4942 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4943 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004944 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004945 }
4946 } catch (RemoteException e) {
4947 // can't happen; the transports are local
4948 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004949 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004950 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004951 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004952 mWakelock.release();
4953 }
4954 }
4955 }
4956
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004957 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004958 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004959 dataChangedImpl(packageName, targets);
4960 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004961
Christopher Tatea3d55342012-03-27 13:16:18 -07004962 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004963 // Record that we need a backup pass for the caller. Since multiple callers
4964 // may share a uid, we need to note all candidates within that uid and schedule
4965 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004966 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004967
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004968 if (targets == null) {
4969 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4970 + " uid=" + Binder.getCallingUid());
4971 return;
4972 }
4973
4974 synchronized (mQueueLock) {
4975 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004976 if (targets.contains(packageName)) {
4977 // Add the caller to the set of pending backups. If there is
4978 // one already there, then overwrite it, but no harm done.
4979 BackupRequest req = new BackupRequest(packageName);
4980 if (mPendingBackups.put(packageName, req) == null) {
4981 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004982
Christopher Tatea3d55342012-03-27 13:16:18 -07004983 // Journal this request in case of crash. The put()
4984 // operation returned null when this package was not already
4985 // in the set; we want to avoid touching the disk redundantly.
4986 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004987
Christopher Tatea3d55342012-03-27 13:16:18 -07004988 if (MORE_DEBUG) {
4989 int numKeys = mPendingBackups.size();
4990 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4991 for (BackupRequest b : mPendingBackups.values()) {
4992 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004993 }
4994 }
4995 }
4996 }
4997 }
4998 }
4999
5000 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07005001 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07005002 // If the caller does not hold the BACKUP permission, it can only request a
5003 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07005004 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07005005 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005006 synchronized (mBackupParticipants) {
5007 return mBackupParticipants.get(Binder.getCallingUid());
5008 }
5009 }
5010
5011 // a caller with full permission can ask to back up any participating app
5012 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07005013 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005014 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07005015 int N = mBackupParticipants.size();
5016 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005017 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07005018 if (s != null) {
5019 targets.addAll(s);
5020 }
5021 }
5022 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005023 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07005024 }
Christopher Tate46758122009-05-06 11:22:00 -07005025
Christopher Tatecde87f42009-06-12 12:55:53 -07005026 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005027 RandomAccessFile out = null;
5028 try {
5029 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5030 out = new RandomAccessFile(mJournal, "rws");
5031 out.seek(out.length());
5032 out.writeUTF(str);
5033 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005034 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005035 mJournal = null;
5036 } finally {
5037 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07005038 }
5039 }
5040
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005041 // ----- IBackupManager binder interface -----
5042
5043 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005044 final int callingUserHandle = UserHandle.getCallingUserId();
5045 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005046 // App is running under a non-owner user profile. For now, we do not back
5047 // up data from secondary user profiles.
5048 // TODO: backups for all user profiles.
5049 if (MORE_DEBUG) {
5050 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5051 + callingUserHandle);
5052 }
5053 return;
5054 }
5055
Christopher Tatea3d55342012-03-27 13:16:18 -07005056 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07005057 if (targets == null) {
5058 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5059 + " uid=" + Binder.getCallingUid());
5060 return;
5061 }
5062
5063 mBackupHandler.post(new Runnable() {
5064 public void run() {
5065 dataChangedImpl(packageName, targets);
5066 }
5067 });
5068 }
5069
Christopher Tateee0e78a2009-07-02 11:17:03 -07005070 // Clear the given package's backup data from the current transport
5071 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005072 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005073 PackageInfo info;
5074 try {
5075 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5076 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005077 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07005078 return;
5079 }
5080
5081 // If the caller does not hold the BACKUP permission, it can only request a
5082 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07005083 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005084 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07005085 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5086 apps = mBackupParticipants.get(Binder.getCallingUid());
5087 } else {
5088 // a caller with full permission can ask to back up any participating app
5089 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08005090 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07005091 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07005092 int N = mBackupParticipants.size();
5093 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07005094 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005095 if (s != null) {
5096 apps.addAll(s);
5097 }
5098 }
5099 }
5100
Christopher Tatea3d55342012-03-27 13:16:18 -07005101 // Is the given app an available participant?
5102 if (apps.contains(packageName)) {
5103 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5104 // found it; fire off the clear request
5105 synchronized (mQueueLock) {
5106 long oldId = Binder.clearCallingIdentity();
5107 mWakelock.acquire();
5108 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5109 new ClearParams(getTransport(mCurrentTransport), info));
5110 mBackupHandler.sendMessage(msg);
5111 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07005112 }
5113 }
5114 }
5115
Christopher Tateace7f092009-06-15 18:07:25 -07005116 // Run a backup pass immediately for any applications that have declared
5117 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07005118 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04005119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07005120
Joe Onorato8a9b2202010-02-26 18:56:32 -08005121 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07005122 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005123 // Because the alarms we are using can jitter, and we want an *immediate*
5124 // backup pass to happen, we restart the timer beginning with "next time,"
5125 // then manually fire the backup trigger intent ourselves.
5126 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07005127 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07005128 mRunBackupIntent.send();
5129 } catch (PendingIntent.CanceledException e) {
5130 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08005131 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07005132 }
Christopher Tate46758122009-05-06 11:22:00 -07005133 }
5134 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005135
Christopher Tated2c0cd42011-09-15 15:51:29 -07005136 boolean deviceIsProvisioned() {
5137 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07005138 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005139 }
5140
Christopher Tate4a627c72011-04-01 14:43:32 -07005141 // Run a *full* backup pass for the given package, writing the resulting data stream
5142 // to the supplied file descriptor. This method is synchronous and does not return
5143 // to the caller until the backup has been completed.
Christopher Tate294b5122013-02-19 14:08:59 -08005144 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5145 boolean includeObbs, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005146 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005147 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5148
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005149 final int callingUserHandle = UserHandle.getCallingUserId();
5150 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005151 throw new IllegalStateException("Backup supported only for the device owner");
5152 }
5153
Christopher Tate4a627c72011-04-01 14:43:32 -07005154 // Validate
5155 if (!doAllApps) {
5156 if (!includeShared) {
5157 // If we're backing up shared data (sdcard or equivalent), then we can run
5158 // without any supplied app names. Otherwise, we'd be doing no work, so
5159 // report the error.
5160 if (pkgList == null || pkgList.length == 0) {
5161 throw new IllegalArgumentException(
5162 "Backup requested but neither shared nor any apps named");
5163 }
5164 }
5165 }
5166
Christopher Tate4a627c72011-04-01 14:43:32 -07005167 long oldId = Binder.clearCallingIdentity();
5168 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005169 // Doesn't make sense to do a full backup prior to setup
5170 if (!deviceIsProvisioned()) {
5171 Slog.i(TAG, "Full backup not supported before setup");
5172 return;
5173 }
5174
5175 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
Christopher Tate294b5122013-02-19 14:08:59 -08005176 + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
Christopher Tated2c0cd42011-09-15 15:51:29 -07005177 + " pkgs=" + pkgList);
5178 Slog.i(TAG, "Beginning full backup...");
5179
Christopher Tate294b5122013-02-19 14:08:59 -08005180 FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5181 includeShared, doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005182 final int token = generateToken();
5183 synchronized (mFullConfirmations) {
5184 mFullConfirmations.put(token, params);
5185 }
5186
Christopher Tate75a99702011-05-18 16:28:19 -07005187 // start up the confirmation UI
5188 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5189 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5190 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005191 mFullConfirmations.delete(token);
5192 return;
5193 }
Christopher Tate75a99702011-05-18 16:28:19 -07005194
5195 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005196 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5197
5198 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005199 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005200
5201 // wait for the backup to be performed
5202 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5203 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005204 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005205 try {
5206 fd.close();
5207 } catch (IOException e) {
5208 // just eat it
5209 }
Christopher Tate75a99702011-05-18 16:28:19 -07005210 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005211 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005212 }
Christopher Tate75a99702011-05-18 16:28:19 -07005213 }
5214
5215 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005216 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005217
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005218 final int callingUserHandle = UserHandle.getCallingUserId();
5219 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005220 throw new IllegalStateException("Restore supported only for the device owner");
5221 }
5222
Christopher Tate75a99702011-05-18 16:28:19 -07005223 long oldId = Binder.clearCallingIdentity();
5224
5225 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005226 // Check whether the device has been provisioned -- we don't handle
5227 // full restores prior to completing the setup process.
5228 if (!deviceIsProvisioned()) {
5229 Slog.i(TAG, "Full restore not permitted before setup");
5230 return;
5231 }
5232
5233 Slog.i(TAG, "Beginning full restore...");
5234
Christopher Tate75a99702011-05-18 16:28:19 -07005235 FullRestoreParams params = new FullRestoreParams(fd);
5236 final int token = generateToken();
5237 synchronized (mFullConfirmations) {
5238 mFullConfirmations.put(token, params);
5239 }
5240
5241 // start up the confirmation UI
5242 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5243 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5244 Slog.e(TAG, "Unable to launch full restore confirmation");
5245 mFullConfirmations.delete(token);
5246 return;
5247 }
5248
5249 // make sure the screen is lit for the user interaction
5250 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5251
5252 // start the confirmation countdown
5253 startConfirmationTimeout(token, params);
5254
5255 // wait for the restore to be performed
5256 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5257 waitForCompletion(params);
5258 } finally {
5259 try {
5260 fd.close();
5261 } catch (IOException e) {
5262 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5263 }
5264 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005265 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005266 }
5267 }
5268
5269 boolean startConfirmationUi(int token, String action) {
5270 try {
5271 Intent confIntent = new Intent(action);
5272 confIntent.setClassName("com.android.backupconfirm",
5273 "com.android.backupconfirm.BackupRestoreConfirmation");
5274 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5275 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5276 mContext.startActivity(confIntent);
5277 } catch (ActivityNotFoundException e) {
5278 return false;
5279 }
5280 return true;
5281 }
5282
5283 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005284 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005285 + TIMEOUT_FULL_CONFIRMATION + " millis");
5286 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5287 token, 0, params);
5288 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005289 }
5290
5291 void waitForCompletion(FullParams params) {
5292 synchronized (params.latch) {
5293 while (params.latch.get() == false) {
5294 try {
5295 params.latch.wait();
5296 } catch (InterruptedException e) { /* never interrupted */ }
5297 }
5298 }
5299 }
5300
5301 void signalFullBackupRestoreCompletion(FullParams params) {
5302 synchronized (params.latch) {
5303 params.latch.set(true);
5304 params.latch.notifyAll();
5305 }
5306 }
5307
5308 // Confirm that the previously-requested full backup/restore operation can proceed. This
5309 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005310 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005311 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005312 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005313 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5314 + " allow=" + allow);
5315
5316 // TODO: possibly require not just this signature-only permission, but even
5317 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005318 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005319
5320 long oldId = Binder.clearCallingIdentity();
5321 try {
5322
5323 FullParams params;
5324 synchronized (mFullConfirmations) {
5325 params = mFullConfirmations.get(token);
5326 if (params != null) {
5327 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5328 mFullConfirmations.delete(token);
5329
5330 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005331 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005332 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005333 : MSG_RUN_FULL_RESTORE;
5334
Christopher Tate728a1c42011-07-28 18:03:03 -07005335 params.observer = observer;
5336 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005337
5338 boolean isEncrypted;
5339 try {
5340 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5341 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5342 } catch (RemoteException e) {
5343 // couldn't contact the mount service; fail "safe" and assume encryption
5344 Slog.e(TAG, "Unable to contact mount service!");
5345 isEncrypted = true;
5346 }
5347 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005348
Christopher Tate75a99702011-05-18 16:28:19 -07005349 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005350 mWakelock.acquire();
5351 Message msg = mBackupHandler.obtainMessage(verb, params);
5352 mBackupHandler.sendMessage(msg);
5353 } else {
5354 Slog.w(TAG, "User rejected full backup/restore operation");
5355 // indicate completion without having actually transferred any data
5356 signalFullBackupRestoreCompletion(params);
5357 }
5358 } else {
5359 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5360 }
5361 }
5362 } finally {
5363 Binder.restoreCallingIdentity(oldId);
5364 }
5365 }
5366
Christopher Tate8031a3d2009-07-06 16:36:05 -07005367 // Enable/disable the backup service
Christopher Tateffe0a802013-09-08 15:41:32 -07005368 @Override
Christopher Tate6ef58a12009-06-29 14:56:28 -07005369 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005371 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005372
Joe Onorato8a9b2202010-02-26 18:56:32 -08005373 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005374
Christopher Tateffe0a802013-09-08 15:41:32 -07005375 long oldId = Binder.clearCallingIdentity();
5376 try {
5377 boolean wasEnabled = mEnabled;
5378 synchronized (this) {
5379 Settings.Secure.putInt(mContext.getContentResolver(),
5380 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
5381 mEnabled = enable;
5382 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005383
Christopher Tateffe0a802013-09-08 15:41:32 -07005384 synchronized (mQueueLock) {
5385 if (enable && !wasEnabled && mProvisioned) {
5386 // if we've just been enabled, start scheduling backup passes
5387 startBackupAlarmsLocked(BACKUP_INTERVAL);
5388 } else if (!enable) {
5389 // No longer enabled, so stop running backups
5390 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005391
Christopher Tateffe0a802013-09-08 15:41:32 -07005392 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005393
Christopher Tateffe0a802013-09-08 15:41:32 -07005394 // This also constitutes an opt-out, so we wipe any data for
5395 // this device from the backend. We start that process with
5396 // an alarm in order to guarantee wakelock states.
5397 if (wasEnabled && mProvisioned) {
5398 // NOTE: we currently flush every registered transport, not just
5399 // the currently-active one.
5400 HashSet<String> allTransports;
5401 synchronized (mTransports) {
5402 allTransports = new HashSet<String>(mTransports.keySet());
5403 }
5404 // build the set of transports for which we are posting an init
5405 for (String transport : allTransports) {
5406 recordInitPendingLocked(true, transport);
5407 }
5408 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5409 mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005410 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07005411 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005412 }
Christopher Tateffe0a802013-09-08 15:41:32 -07005413 } finally {
5414 Binder.restoreCallingIdentity(oldId);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005415 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005416 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005417
Christopher Tatecce9da52010-02-03 15:11:15 -08005418 // Enable/disable automatic restore of app data at install time
5419 public void setAutoRestore(boolean doAutoRestore) {
5420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005421 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005422
Joe Onorato8a9b2202010-02-26 18:56:32 -08005423 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005424
5425 synchronized (this) {
5426 Settings.Secure.putInt(mContext.getContentResolver(),
5427 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5428 mAutoRestore = doAutoRestore;
5429 }
5430 }
5431
Christopher Tate8031a3d2009-07-06 16:36:05 -07005432 // Mark the backup service as having been provisioned
5433 public void setBackupProvisioned(boolean available) {
5434 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5435 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005436 /*
5437 * This is now a no-op; provisioning is simply the device's own setup state.
5438 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005439 }
5440
5441 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005442 // We used to use setInexactRepeating(), but that may be linked to
5443 // backups running at :00 more often than not, creating load spikes.
5444 // Schedule at an exact time for now, and also add a bit of "fuzz".
5445
5446 Random random = new Random();
5447 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5448 random.nextInt(FUZZ_MILLIS);
5449 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5450 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005451 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005452 }
5453
Christopher Tate6ef58a12009-06-29 14:56:28 -07005454 // Report whether the backup mechanism is currently enabled
5455 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005456 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005457 return mEnabled; // no need to synchronize just to read it
5458 }
5459
Christopher Tate91717492009-06-26 21:07:13 -07005460 // Report the name of the currently active transport
5461 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005462 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005463 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005464 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005465 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005466 }
5467
Christopher Tate91717492009-06-26 21:07:13 -07005468 // Report all known, available backup transports
5469 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005470 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005471
Christopher Tate91717492009-06-26 21:07:13 -07005472 String[] list = null;
5473 ArrayList<String> known = new ArrayList<String>();
5474 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5475 if (entry.getValue() != null) {
5476 known.add(entry.getKey());
5477 }
5478 }
5479
5480 if (known.size() > 0) {
5481 list = new String[known.size()];
5482 known.toArray(list);
5483 }
5484 return list;
5485 }
5486
5487 // Select which transport to use for the next backup operation. If the given
5488 // name is not one of the available transports, no action is taken and the method
5489 // returns null.
5490 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005492
5493 synchronized (mTransports) {
5494 String prevTransport = null;
5495 if (mTransports.get(transport) != null) {
5496 prevTransport = mCurrentTransport;
5497 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005498 Settings.Secure.putString(mContext.getContentResolver(),
5499 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005500 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005501 + " returning " + prevTransport);
5502 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005503 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005504 }
5505 return prevTransport;
5506 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005507 }
5508
Christopher Tatef5e1c292010-12-08 18:40:26 -08005509 // Supply the configuration Intent for the given transport. If the name is not one
5510 // of the available transports, or if the transport does not supply any configuration
5511 // UI, the method returns null.
5512 public Intent getConfigurationIntent(String transportName) {
5513 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5514 "getConfigurationIntent");
5515
5516 synchronized (mTransports) {
5517 final IBackupTransport transport = mTransports.get(transportName);
5518 if (transport != null) {
5519 try {
5520 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005521 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005522 + intent);
5523 return intent;
5524 } catch (RemoteException e) {
5525 /* fall through to return null */
5526 }
5527 }
5528 }
5529
5530 return null;
5531 }
5532
5533 // Supply the configuration summary string for the given transport. If the name is
5534 // not one of the available transports, or if the transport does not supply any
5535 // summary / destination string, the method can return null.
5536 //
5537 // This string is used VERBATIM as the summary text of the relevant Settings item!
5538 public String getDestinationString(String transportName) {
5539 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005540 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005541
5542 synchronized (mTransports) {
5543 final IBackupTransport transport = mTransports.get(transportName);
5544 if (transport != null) {
5545 try {
5546 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005547 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005548 return text;
5549 } catch (RemoteException e) {
5550 /* fall through to return null */
5551 }
5552 }
5553 }
5554
5555 return null;
5556 }
5557
Christopher Tate043dadc2009-06-02 16:11:00 -07005558 // Callback: a requested backup agent has been instantiated. This should only
5559 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005560 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005561 synchronized(mAgentConnectLock) {
5562 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005563 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005564 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5565 mConnectedAgent = agent;
5566 mConnecting = false;
5567 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005568 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005569 + " claiming agent connected");
5570 }
5571 mAgentConnectLock.notifyAll();
5572 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005573 }
5574
5575 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5576 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005577 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005578 public void agentDisconnected(String packageName) {
5579 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005580 synchronized(mAgentConnectLock) {
5581 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5582 mConnectedAgent = null;
5583 mConnecting = false;
5584 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005585 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005586 + " claiming agent disconnected");
5587 }
5588 mAgentConnectLock.notifyAll();
5589 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005590 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005591
Christopher Tate1bb69062010-02-19 17:02:12 -08005592 // An application being installed will need a restore pass, then the Package Manager
5593 // will need to be told when the restore is finished.
5594 public void restoreAtInstall(String packageName, int token) {
5595 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005596 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005597 + " attemping install-time restore");
5598 return;
5599 }
5600
5601 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005602 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005603 + " token=" + Integer.toHexString(token)
5604 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005605
Christopher Tatef0872722010-02-25 15:22:48 -08005606 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005607 // okay, we're going to attempt a restore of this package from this restore set.
5608 // The eventual message back into the Package Manager to run the post-install
5609 // steps for 'token' will be issued from the restore handling code.
5610
5611 // We can use a synthetic PackageInfo here because:
5612 // 1. We know it's valid, since the Package Manager supplied the name
5613 // 2. Only the packageName field will be used by the restore code
5614 PackageInfo pkg = new PackageInfo();
5615 pkg.packageName = packageName;
5616
5617 mWakelock.acquire();
5618 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5619 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005620 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005621 mBackupHandler.sendMessage(msg);
5622 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005623 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5624 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005625 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005626 try {
5627 mPackageManagerBinder.finishPackageInstall(token);
5628 } catch (RemoteException e) { /* can't happen */ }
5629 }
5630 }
5631
Christopher Tate8c850b72009-06-07 19:33:20 -07005632 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005633 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5634 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5635 + " transport=" + transport);
5636
5637 boolean needPermission = true;
5638 if (transport == null) {
5639 transport = mCurrentTransport;
5640
5641 if (packageName != null) {
5642 PackageInfo app = null;
5643 try {
5644 app = mPackageManager.getPackageInfo(packageName, 0);
5645 } catch (NameNotFoundException nnf) {
5646 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5647 throw new IllegalArgumentException("Package " + packageName + " not found");
5648 }
5649
5650 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5651 // So: using the current active transport, and the caller has asked
5652 // that its own package will be restored. In this narrow use case
5653 // we do not require the caller to hold the permission.
5654 needPermission = false;
5655 }
5656 }
5657 }
5658
5659 if (needPermission) {
5660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5661 "beginRestoreSession");
5662 } else {
5663 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5664 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005665
5666 synchronized(this) {
5667 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005668 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005669 return null;
5670 }
Chris Tate44ab8452010-11-16 15:10:49 -08005671 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005672 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005673 }
5674 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005675 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005676
Christopher Tate73a3cb32010-12-13 18:27:26 -08005677 void clearRestoreSession(ActiveRestoreSession currentSession) {
5678 synchronized(this) {
5679 if (currentSession != mActiveRestoreSession) {
5680 Slog.e(TAG, "ending non-current restore session");
5681 } else {
5682 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5683 mActiveRestoreSession = null;
5684 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5685 }
5686 }
5687 }
5688
Christopher Tate44a27902010-01-27 17:15:49 -08005689 // Note that a currently-active backup agent has notified us that it has
5690 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005691 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005692 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005693 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5694 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005695 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005696 op = mCurrentOperations.get(token);
5697 if (op != null) {
5698 op.state = OP_ACKNOWLEDGED;
5699 }
Christopher Tate44a27902010-01-27 17:15:49 -08005700 mCurrentOpLock.notifyAll();
5701 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005702
5703 // The completion callback, if any, is invoked on the handler
5704 if (op != null && op.callback != null) {
5705 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5706 mBackupHandler.sendMessage(msg);
5707 }
Christopher Tate44a27902010-01-27 17:15:49 -08005708 }
5709
Christopher Tate9b3905c2009-06-08 15:24:01 -07005710 // ----- Restore session -----
5711
Christopher Tate80202c82010-01-25 19:37:47 -08005712 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005713 private static final String TAG = "RestoreSession";
5714
Chris Tate44ab8452010-11-16 15:10:49 -08005715 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005716 private IBackupTransport mRestoreTransport = null;
5717 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005718 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005719
Chris Tate44ab8452010-11-16 15:10:49 -08005720 ActiveRestoreSession(String packageName, String transport) {
5721 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005722 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005723 }
5724
5725 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005726 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005727 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005728 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005729 if (observer == null) {
5730 throw new IllegalArgumentException("Observer must not be null");
5731 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005732
Christopher Tate73a3cb32010-12-13 18:27:26 -08005733 if (mEnded) {
5734 throw new IllegalStateException("Restore session already ended");
5735 }
5736
Christopher Tate1bb69062010-02-19 17:02:12 -08005737 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005738 try {
Christopher Tate43383042009-07-13 15:17:13 -07005739 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005740 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005741 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005742 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005743 // spin off the transport request to our service thread
5744 mWakelock.acquire();
5745 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5746 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5747 mBackupHandler.sendMessage(msg);
5748 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005749 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005750 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005751 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005752 } finally {
5753 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005754 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005755 }
5756
Christopher Tate84725812010-02-04 15:52:40 -08005757 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5759 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005760
Chris Tate44ab8452010-11-16 15:10:49 -08005761 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005762 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005763
Christopher Tate73a3cb32010-12-13 18:27:26 -08005764 if (mEnded) {
5765 throw new IllegalStateException("Restore session already ended");
5766 }
5767
Dan Egnor0084da52009-07-29 12:57:16 -07005768 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005769 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5770 return -1;
5771 }
5772
5773 if (mPackageName != null) {
5774 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005775 return -1;
5776 }
5777
Christopher Tate21ab6a52009-09-24 18:01:46 -07005778 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005779 for (int i = 0; i < mRestoreSets.length; i++) {
5780 if (token == mRestoreSets[i].token) {
5781 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005782 mWakelock.acquire();
5783 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005784 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005785 mBackupHandler.sendMessage(msg);
5786 Binder.restoreCallingIdentity(oldId);
5787 return 0;
5788 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005789 }
5790 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005791
Joe Onorato8a9b2202010-02-26 18:56:32 -08005792 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005793 return -1;
5794 }
5795
Christopher Tate284f1bb2011-07-07 14:31:18 -07005796 public synchronized int restoreSome(long token, IRestoreObserver observer,
5797 String[] packages) {
5798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5799 "performRestore");
5800
5801 if (DEBUG) {
5802 StringBuilder b = new StringBuilder(128);
5803 b.append("restoreSome token=");
5804 b.append(Long.toHexString(token));
5805 b.append(" observer=");
5806 b.append(observer.toString());
5807 b.append(" packages=");
5808 if (packages == null) {
5809 b.append("null");
5810 } else {
5811 b.append('{');
5812 boolean first = true;
5813 for (String s : packages) {
5814 if (!first) {
5815 b.append(", ");
5816 } else first = false;
5817 b.append(s);
5818 }
5819 b.append('}');
5820 }
5821 Slog.d(TAG, b.toString());
5822 }
5823
5824 if (mEnded) {
5825 throw new IllegalStateException("Restore session already ended");
5826 }
5827
5828 if (mRestoreTransport == null || mRestoreSets == null) {
5829 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5830 return -1;
5831 }
5832
5833 if (mPackageName != null) {
5834 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5835 return -1;
5836 }
5837
5838 synchronized (mQueueLock) {
5839 for (int i = 0; i < mRestoreSets.length; i++) {
5840 if (token == mRestoreSets[i].token) {
5841 long oldId = Binder.clearCallingIdentity();
5842 mWakelock.acquire();
5843 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5844 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5845 packages, true);
5846 mBackupHandler.sendMessage(msg);
5847 Binder.restoreCallingIdentity(oldId);
5848 return 0;
5849 }
5850 }
5851 }
5852
5853 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5854 return -1;
5855 }
5856
Christopher Tate84725812010-02-04 15:52:40 -08005857 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005858 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005859
Christopher Tate73a3cb32010-12-13 18:27:26 -08005860 if (mEnded) {
5861 throw new IllegalStateException("Restore session already ended");
5862 }
5863
Chris Tate44ab8452010-11-16 15:10:49 -08005864 if (mPackageName != null) {
5865 if (! mPackageName.equals(packageName)) {
5866 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5867 + " on session for package " + mPackageName);
5868 return -1;
5869 }
5870 }
5871
Christopher Tate84725812010-02-04 15:52:40 -08005872 PackageInfo app = null;
5873 try {
5874 app = mPackageManager.getPackageInfo(packageName, 0);
5875 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005876 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005877 return -1;
5878 }
5879
5880 // If the caller is not privileged and is not coming from the target
5881 // app's uid, throw a permission exception back to the caller.
5882 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5883 Binder.getCallingPid(), Binder.getCallingUid());
5884 if ((perm == PackageManager.PERMISSION_DENIED) &&
5885 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005886 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005887 + " or calling uid=" + Binder.getCallingUid());
5888 throw new SecurityException("No permission to restore other packages");
5889 }
5890
Christopher Tate7d411a32010-02-26 11:27:08 -08005891 // If the package has no backup agent, we obviously cannot proceed
5892 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005893 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005894 return -1;
5895 }
5896
Christopher Tate84725812010-02-04 15:52:40 -08005897 // So far so good; we're allowed to try to restore this package. Now
5898 // check whether there is data for it in the current dataset, falling back
5899 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005900 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005901
5902 // If we didn't come up with a place to look -- no ancestral dataset and
5903 // the app has never been backed up from this device -- there's nothing
5904 // to do but return failure.
5905 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005906 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005907 return -1;
5908 }
5909
5910 // Ready to go: enqueue the restore request and claim success
5911 long oldId = Binder.clearCallingIdentity();
5912 mWakelock.acquire();
5913 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005914 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005915 mBackupHandler.sendMessage(msg);
5916 Binder.restoreCallingIdentity(oldId);
5917 return 0;
5918 }
5919
Christopher Tate73a3cb32010-12-13 18:27:26 -08005920 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5921 class EndRestoreRunnable implements Runnable {
5922 BackupManagerService mBackupManager;
5923 ActiveRestoreSession mSession;
5924
5925 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5926 mBackupManager = manager;
5927 mSession = session;
5928 }
5929
5930 public void run() {
5931 // clean up the session's bookkeeping
5932 synchronized (mSession) {
5933 try {
5934 if (mSession.mRestoreTransport != null) {
5935 mSession.mRestoreTransport.finishRestore();
5936 }
5937 } catch (Exception e) {
5938 Slog.e(TAG, "Error in finishRestore", e);
5939 } finally {
5940 mSession.mRestoreTransport = null;
5941 mSession.mEnded = true;
5942 }
5943 }
5944
5945 // clean up the BackupManagerService side of the bookkeeping
5946 // and cancel any pending timeout message
5947 mBackupManager.clearRestoreSession(mSession);
5948 }
5949 }
5950
Dan Egnor0084da52009-07-29 12:57:16 -07005951 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005952 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005953
Christopher Tate73a3cb32010-12-13 18:27:26 -08005954 if (mEnded) {
5955 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005956 }
5957
Christopher Tate73a3cb32010-12-13 18:27:26 -08005958 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005959 }
5960 }
5961
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005962 @Override
5963 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5965
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005966 long identityToken = Binder.clearCallingIdentity();
5967 try {
5968 dumpInternal(pw);
5969 } finally {
5970 Binder.restoreCallingIdentity(identityToken);
5971 }
5972 }
5973
5974 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005975 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005976 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005977 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005978 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005979 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005980 if (mBackupRunning) pw.println("Backup currently running");
5981 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005982 + " (now = " + System.currentTimeMillis() + ')');
5983 pw.println(" next scheduled: " + mNextBackupPass);
5984
Christopher Tate91717492009-06-26 21:07:13 -07005985 pw.println("Available transports:");
5986 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005987 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5988 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005989 IBackupTransport transport = getTransport(t);
5990 File dir = new File(mBaseStateDir, transport.transportDirName());
5991 pw.println(" destination: " + transport.currentDestinationString());
5992 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005993 for (File f : dir.listFiles()) {
5994 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5995 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005996 } catch (Exception e) {
5997 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005998 pw.println(" Error: " + e);
5999 }
Christopher Tate91717492009-06-26 21:07:13 -07006000 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006001
6002 pw.println("Pending init: " + mPendingInits.size());
6003 for (String s : mPendingInits) {
6004 pw.println(" " + s);
6005 }
6006
Christopher Tate6de74ff2012-01-17 15:20:32 -08006007 if (DEBUG_BACKUP_TRACE) {
6008 synchronized (mBackupTrace) {
6009 if (!mBackupTrace.isEmpty()) {
6010 pw.println("Most recent backup trace:");
6011 for (String s : mBackupTrace) {
6012 pw.println(" " + s);
6013 }
6014 }
6015 }
6016 }
6017
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006018 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07006019 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006020 for (int i=0; i<N; i++) {
6021 int uid = mBackupParticipants.keyAt(i);
6022 pw.print(" uid: ");
6023 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07006024 HashSet<String> participants = mBackupParticipants.valueAt(i);
6025 for (String app: participants) {
6026 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006027 }
6028 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006029
Christopher Tateb49ceb32010-02-08 16:22:24 -08006030 pw.println("Ancestral packages: "
6031 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07006032 if (mAncestralPackages != null) {
6033 for (String pkg : mAncestralPackages) {
6034 pw.println(" " + pkg);
6035 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08006036 }
6037
Christopher Tate73e02522009-07-15 14:18:26 -07006038 pw.println("Ever backed up: " + mEverStoredApps.size());
6039 for (String pkg : mEverStoredApps) {
6040 pw.println(" " + pkg);
6041 }
Christopher Tate55f931a2009-09-29 17:17:34 -07006042
6043 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07006044 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07006045 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07006046 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07006047 }
6048 }
Christopher Tate487529a2009-04-29 14:03:25 -07006049}