blob: f241c8090dbc3ed7f568bb4fcbdf7c71a1df450c [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate79ec80d2011-06-24 14:58:49 -070026import android.app.backup.BackupAgent;
Christopher Tate4a627c72011-04-01 14:43:32 -070027import android.app.backup.BackupDataOutput;
28import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060029import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070031import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070034import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.ComponentName;
Christopher Tated2c0cd42011-09-15 15:51:29 -070037import android.content.ContentResolver;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.content.Context;
39import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070041import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070042import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070043import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070044import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070045import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080046import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070047import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070048import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060049import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060050import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate97ea1222012-05-17 14:59:41 -070051import android.database.ContentObserver;
Christopher Tate3799bc22009-05-06 16:13:56 -070052import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070054import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070055import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080060import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070062import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070063import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070064import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.os.RemoteException;
Christopher Tate32418be2011-10-10 13:51:12 -070066import android.os.ServiceManager;
Dan Egnorbb9001c2009-07-27 12:20:13 -070067import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070069import android.os.WorkSource;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070070import android.os.Environment.UserEnvironment;
Christopher Tate32418be2011-10-10 13:51:12 -070071import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080072import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070073import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070074import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080075import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070076import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070077import android.util.StringBuilderPrinter;
78
Jason parksa3cdaa52011-01-13 14:15:43 -060079import com.android.internal.backup.BackupConstants;
80import com.android.internal.backup.IBackupTransport;
81import com.android.internal.backup.LocalTransport;
82import com.android.server.PackageManagerBackupAgent.Metadata;
83
Christopher Tate2efd2db2011-07-19 16:32:49 -070084import java.io.BufferedInputStream;
85import java.io.BufferedOutputStream;
86import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070087import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070088import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070089import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070090import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070091import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070092import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080093import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070094import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070095import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070096import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070097import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070098import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070099import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700100import java.security.InvalidAlgorithmParameterException;
101import java.security.InvalidKeyException;
102import java.security.Key;
103import java.security.NoSuchAlgorithmException;
104import java.security.SecureRandom;
105import java.security.spec.InvalidKeySpecException;
106import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700107import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400108import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700109import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700110import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400111import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700112import java.util.HashSet;
113import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700114import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700115import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800116import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700117import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700118import java.util.zip.Deflater;
119import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700120import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700121
Christopher Tate2efd2db2011-07-19 16:32:49 -0700122import javax.crypto.BadPaddingException;
123import javax.crypto.Cipher;
124import javax.crypto.CipherInputStream;
125import javax.crypto.CipherOutputStream;
126import javax.crypto.IllegalBlockSizeException;
127import javax.crypto.NoSuchPaddingException;
128import javax.crypto.SecretKey;
129import javax.crypto.SecretKeyFactory;
130import javax.crypto.spec.IvParameterSpec;
131import javax.crypto.spec.PBEKeySpec;
132import javax.crypto.spec.SecretKeySpec;
133
Christopher Tate487529a2009-04-29 14:03:25 -0700134class BackupManagerService extends IBackupManager.Stub {
135 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700136 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700137 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700138
139 // Name and current contents version of the full-backup manifest file
140 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
141 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700142 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
143 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700144 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700145
Christopher Tate73d73692012-01-20 17:11:31 -0800146 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
147
Christopher Tate49401dd2009-07-01 12:34:29 -0700148 // How often we perform a backup pass. Privileged external callers can
149 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700150 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700151
Dan Egnorc1c49c02009-10-30 17:35:39 -0700152 // Random variation in backup scheduling time to avoid server load spikes
153 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
154
Christopher Tate8031a3d2009-07-06 16:36:05 -0700155 // The amount of time between the initial provisioning of the device and
156 // the first backup pass.
157 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
158
Christopher Tate45281862010-03-05 15:46:30 -0800159 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
160 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
161 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700162 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700163 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700164 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700165 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700166 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700167 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
168 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800169 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700170 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
171 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700172
Christopher Tate8e294d42011-08-31 20:37:12 -0700173 // backup task state machine tick
174 static final int MSG_BACKUP_RESTORE_STEP = 20;
175 static final int MSG_OP_COMPLETE = 21;
176
Christopher Tatec7b31e32009-06-10 15:49:30 -0700177 // Timeout interval for deciding that a bind or clear-data has taken too long
178 static final long TIMEOUT_INTERVAL = 10 * 1000;
179
Christopher Tate44a27902010-01-27 17:15:49 -0800180 // Timeout intervals for agent backup & restore operations
181 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700182 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700183 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800184 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
185
Christopher Tate2efd2db2011-07-19 16:32:49 -0700186 // User confirmation timeout for a full backup/restore operation. It's this long in
187 // order to give them time to enter the backup password.
188 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700189
Christopher Tate487529a2009-04-29 14:03:25 -0700190 private Context mContext;
191 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800192 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700193 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700194 private PowerManager mPowerManager;
195 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700196 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800197 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700198
Christopher Tate73e02522009-07-15 14:18:26 -0700199 boolean mEnabled; // access to this is synchronized on 'this'
200 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800201 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700202 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800203 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800204 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700205 PendingIntent mRunBackupIntent, mRunInitIntent;
206 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700207 // map UIDs to the set of participating packages under that UID
208 final SparseArray<HashSet<String>> mBackupParticipants
209 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700210 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700211 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700212 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700213
Christopher Tatecc55f812011-08-16 16:06:53 -0700214 BackupRequest(String pkgName) {
215 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700216 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700217
218 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700219 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700220 }
Christopher Tate46758122009-05-06 11:22:00 -0700221 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800222 // Backups that we haven't started yet. Keys are package names.
223 HashMap<String,BackupRequest> mPendingBackups
224 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700225
226 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700227 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700228
229 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700230 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700231
Christopher Tate043dadc2009-06-02 16:11:00 -0700232 // The thread performing the sequence of queued backups binds to each app's agent
233 // in succession. Bind notifications are asynchronously delivered through the
234 // Activity Manager; use this lock object to signal when a requested binding has
235 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700236 final Object mAgentConnectLock = new Object();
237 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700238 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700239 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700240 volatile long mLastBackupPass;
241 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700242
Christopher Tate6de74ff2012-01-17 15:20:32 -0800243 // For debugging, we maintain a progress trace of operations during backup
244 static final boolean DEBUG_BACKUP_TRACE = true;
245 final List<String> mBackupTrace = new ArrayList<String>();
246
Christopher Tate55f931a2009-09-29 17:17:34 -0700247 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700248 final Object mClearDataLock = new Object();
249 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700250
Christopher Tate91717492009-06-26 21:07:13 -0700251 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700252 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700253 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700254 String mCurrentTransport;
255 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800256 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700257
Christopher Tate97ea1222012-05-17 14:59:41 -0700258 // Watch the device provisioning operation during setup
259 ContentObserver mProvisionedObserver;
260
261 class ProvisionedObserver extends ContentObserver {
262 public ProvisionedObserver(Handler handler) {
263 super(handler);
264 }
265
266 public void onChange(boolean selfChange) {
267 final boolean wasProvisioned = mProvisioned;
268 final boolean isProvisioned = deviceIsProvisioned();
269 // latch: never unprovision
270 mProvisioned = wasProvisioned || isProvisioned;
271 if (MORE_DEBUG) {
272 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
273 + " is=" + isProvisioned + " now=" + mProvisioned);
274 }
275
276 synchronized (mQueueLock) {
277 if (mProvisioned && !wasProvisioned && mEnabled) {
278 // we're now good to go, so start the backup alarms
279 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
280 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
281 }
282 }
283 }
284 }
285
Christopher Tate2d449afe2010-03-29 19:14:24 -0700286 class RestoreGetSetsParams {
287 public IBackupTransport transport;
288 public ActiveRestoreSession session;
289 public IRestoreObserver observer;
290
291 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
292 IRestoreObserver _observer) {
293 transport = _transport;
294 session = _session;
295 observer = _observer;
296 }
297 }
298
Christopher Tate73e02522009-07-15 14:18:26 -0700299 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700300 public IBackupTransport transport;
301 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700302 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800303 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800304 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700305 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700306 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800307
308 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700309 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800310 transport = _transport;
311 observer = _obs;
312 token = _token;
313 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800314 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700315 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700316 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800317 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700318
Chris Tate249345b2010-10-29 12:57:04 -0700319 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
320 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700321 transport = _transport;
322 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700323 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800324 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800325 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700326 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700327 filterSet = null;
328 }
329
330 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
331 String[] _filterSet, boolean _needFullBackup) {
332 transport = _transport;
333 observer = _obs;
334 token = _token;
335 pkgInfo = null;
336 pmToken = 0;
337 needFullBackup = _needFullBackup;
338 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700339 }
340 }
341
Christopher Tate73e02522009-07-15 14:18:26 -0700342 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700343 public IBackupTransport transport;
344 public PackageInfo packageInfo;
345
346 ClearParams(IBackupTransport _transport, PackageInfo _info) {
347 transport = _transport;
348 packageInfo = _info;
349 }
350 }
351
Christopher Tate4a627c72011-04-01 14:43:32 -0700352 class FullParams {
353 public ParcelFileDescriptor fd;
354 public final AtomicBoolean latch;
355 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700356 public String curPassword; // filled in by the confirmation step
357 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700358
359 FullParams() {
360 latch = new AtomicBoolean(false);
361 }
362 }
363
364 class FullBackupParams extends FullParams {
365 public boolean includeApks;
366 public boolean includeShared;
367 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700368 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700369 public String[] packages;
370
371 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700372 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700373 fd = output;
374 includeApks = saveApks;
375 includeShared = saveShared;
376 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700377 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700378 packages = pkgList;
379 }
380 }
381
382 class FullRestoreParams extends FullParams {
383 FullRestoreParams(ParcelFileDescriptor input) {
384 fd = input;
385 }
386 }
387
Christopher Tate44a27902010-01-27 17:15:49 -0800388 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
389 // token is the index of the entry in the pending-operations list.
390 static final int OP_PENDING = 0;
391 static final int OP_ACKNOWLEDGED = 1;
392 static final int OP_TIMEOUT = -1;
393
Christopher Tate8e294d42011-08-31 20:37:12 -0700394 class Operation {
395 public int state;
396 public BackupRestoreTask callback;
397
398 Operation(int initialState, BackupRestoreTask callbackObj) {
399 state = initialState;
400 callback = callbackObj;
401 }
402 }
403 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800404 final Object mCurrentOpLock = new Object();
405 final Random mTokenGenerator = new Random();
406
Christopher Tate4a627c72011-04-01 14:43:32 -0700407 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
408
Christopher Tate5cb400b2009-06-25 16:03:14 -0700409 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700410 File mBaseStateDir;
411 File mDataDir;
412 File mJournalDir;
413 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700414
Christopher Tate2efd2db2011-07-19 16:32:49 -0700415 // Backup password, if any, and the file where it's saved. What is stored is not the
416 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
417 // persisted) salt. Validation is performed by running the challenge text through the
418 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
419 // the saved hash string, then the challenge text matches the originally supplied
420 // password text.
421 private final SecureRandom mRng = new SecureRandom();
422 private String mPasswordHash;
423 private File mPasswordHashFile;
424 private byte[] mPasswordSalt;
425
426 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
427 static final int PBKDF2_HASH_ROUNDS = 10000;
428 static final int PBKDF2_KEY_SIZE = 256; // bits
429 static final int PBKDF2_SALT_SIZE = 512; // bits
430 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
431
Christopher Tate84725812010-02-04 15:52:40 -0800432 // Keep a log of all the apps we've ever backed up, and what the
433 // dataset tokens are for both the current backup dataset and
434 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700435 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700436 HashSet<String> mEverStoredApps = new HashSet<String>();
437
Christopher Tateb49ceb32010-02-08 16:22:24 -0800438 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800439 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800440 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800441 long mAncestralToken = 0;
442 long mCurrentToken = 0;
443
Christopher Tate4cc86e12009-09-21 19:36:51 -0700444 // Persistently track the need to do a full init
445 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
446 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700447
Christopher Tate4a627c72011-04-01 14:43:32 -0700448 // Utility: build a new random integer token
449 int generateToken() {
450 int token;
451 do {
452 synchronized (mTokenGenerator) {
453 token = mTokenGenerator.nextInt();
454 }
455 } while (token < 0);
456 return token;
457 }
458
Christopher Tate44a27902010-01-27 17:15:49 -0800459 // ----- Asynchronous backup/restore handler thread -----
460
461 private class BackupHandler extends Handler {
462 public BackupHandler(Looper looper) {
463 super(looper);
464 }
465
466 public void handleMessage(Message msg) {
467
468 switch (msg.what) {
469 case MSG_RUN_BACKUP:
470 {
471 mLastBackupPass = System.currentTimeMillis();
472 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
473
474 IBackupTransport transport = getTransport(mCurrentTransport);
475 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800476 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700477 synchronized (mQueueLock) {
478 mBackupRunning = false;
479 }
Christopher Tate44a27902010-01-27 17:15:49 -0800480 mWakelock.release();
481 break;
482 }
483
484 // snapshot the pending-backup set and work on that
485 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800486 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800487 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800488 // Do we have any work to do? Construct the work queue
489 // then release the synchronization lock to actually run
490 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800491 if (mPendingBackups.size() > 0) {
492 for (BackupRequest b: mPendingBackups.values()) {
493 queue.add(b);
494 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800495 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800496 mPendingBackups.clear();
497
498 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800499 mJournal = null;
500
Christopher Tate44a27902010-01-27 17:15:49 -0800501 }
502 }
Christopher Tatec61da312010-02-05 10:41:27 -0800503
Christopher Tate8e294d42011-08-31 20:37:12 -0700504 // At this point, we have started a new journal file, and the old
505 // file identity is being passed to the backup processing task.
506 // When it completes successfully, that old journal file will be
507 // deleted. If we crash prior to that, the old journal is parsed
508 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800509 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700510 // Spin up a backup state sequence and set it running
511 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
512 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
513 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800514 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800515 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700516 synchronized (mQueueLock) {
517 mBackupRunning = false;
518 }
Christopher Tatec61da312010-02-05 10:41:27 -0800519 mWakelock.release();
520 }
Christopher Tate44a27902010-01-27 17:15:49 -0800521 break;
522 }
523
Christopher Tate8e294d42011-08-31 20:37:12 -0700524 case MSG_BACKUP_RESTORE_STEP:
525 {
526 try {
527 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
528 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
529 task.execute();
530 } catch (ClassCastException e) {
531 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
532 }
533 break;
534 }
535
536 case MSG_OP_COMPLETE:
537 {
538 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700539 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
540 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700541 } catch (ClassCastException e) {
542 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
543 }
544 break;
545 }
546
Christopher Tate44a27902010-01-27 17:15:49 -0800547 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700548 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700549 // TODO: refactor full backup to be a looper-based state machine
550 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700551 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700552 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
553 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700554 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700555 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700556 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800557 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700558 }
Christopher Tate44a27902010-01-27 17:15:49 -0800559
560 case MSG_RUN_RESTORE:
561 {
562 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800563 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700564 PerformRestoreTask task = new PerformRestoreTask(
565 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700566 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700567 params.needFullBackup, params.filterSet);
568 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
569 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800570 break;
571 }
572
Christopher Tate75a99702011-05-18 16:28:19 -0700573 case MSG_RUN_FULL_RESTORE:
574 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700575 // TODO: refactor full restore to be a looper-based state machine
576 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700577 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700578 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
579 params.curPassword, params.encryptPassword,
580 params.observer, params.latch);
581 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700582 break;
583 }
584
Christopher Tate44a27902010-01-27 17:15:49 -0800585 case MSG_RUN_CLEAR:
586 {
587 ClearParams params = (ClearParams)msg.obj;
588 (new PerformClearTask(params.transport, params.packageInfo)).run();
589 break;
590 }
591
592 case MSG_RUN_INITIALIZE:
593 {
594 HashSet<String> queue;
595
596 // Snapshot the pending-init queue and work on that
597 synchronized (mQueueLock) {
598 queue = new HashSet<String>(mPendingInits);
599 mPendingInits.clear();
600 }
601
602 (new PerformInitializeTask(queue)).run();
603 break;
604 }
605
Christopher Tate2d449afe2010-03-29 19:14:24 -0700606 case MSG_RUN_GET_RESTORE_SETS:
607 {
608 // Like other async operations, this is entered with the wakelock held
609 RestoreSet[] sets = null;
610 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
611 try {
612 sets = params.transport.getAvailableRestoreSets();
613 // cache the result in the active session
614 synchronized (params.session) {
615 params.session.mRestoreSets = sets;
616 }
617 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
618 } catch (Exception e) {
619 Slog.e(TAG, "Error from transport getting set list");
620 } finally {
621 if (params.observer != null) {
622 try {
623 params.observer.restoreSetsAvailable(sets);
624 } catch (RemoteException re) {
625 Slog.e(TAG, "Unable to report listing to observer");
626 } catch (Exception e) {
627 Slog.e(TAG, "Restore observer threw", e);
628 }
629 }
630
Christopher Tate2a935092011-03-03 17:30:32 -0800631 // Done: reset the session timeout clock
632 removeMessages(MSG_RESTORE_TIMEOUT);
633 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
634
Christopher Tate2d449afe2010-03-29 19:14:24 -0700635 mWakelock.release();
636 }
637 break;
638 }
639
Christopher Tate44a27902010-01-27 17:15:49 -0800640 case MSG_TIMEOUT:
641 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700642 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800643 break;
644 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800645
646 case MSG_RESTORE_TIMEOUT:
647 {
648 synchronized (BackupManagerService.this) {
649 if (mActiveRestoreSession != null) {
650 // Client app left the restore session dangling. We know that it
651 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700652 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800653 // up now.
654 Slog.w(TAG, "Restore session timed out; aborting");
655 post(mActiveRestoreSession.new EndRestoreRunnable(
656 BackupManagerService.this, mActiveRestoreSession));
657 }
658 }
659 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700660
661 case MSG_FULL_CONFIRMATION_TIMEOUT:
662 {
663 synchronized (mFullConfirmations) {
664 FullParams params = mFullConfirmations.get(msg.arg1);
665 if (params != null) {
666 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
667
668 // Release the waiter; timeout == completion
669 signalFullBackupRestoreCompletion(params);
670
671 // Remove the token from the set
672 mFullConfirmations.delete(msg.arg1);
673
674 // Report a timeout to the observer, if any
675 if (params.observer != null) {
676 try {
677 params.observer.onTimeout();
678 } catch (RemoteException e) {
679 /* don't care if the app has gone away */
680 }
681 }
682 } else {
683 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
684 }
685 }
686 break;
687 }
Christopher Tate44a27902010-01-27 17:15:49 -0800688 }
689 }
690 }
691
Christopher Tate6de74ff2012-01-17 15:20:32 -0800692 // ----- Debug-only backup operation trace -----
693 void addBackupTrace(String s) {
694 if (DEBUG_BACKUP_TRACE) {
695 synchronized (mBackupTrace) {
696 mBackupTrace.add(s);
697 }
698 }
699 }
700
701 void clearBackupTrace() {
702 if (DEBUG_BACKUP_TRACE) {
703 synchronized (mBackupTrace) {
704 mBackupTrace.clear();
705 }
706 }
707 }
708
Christopher Tate44a27902010-01-27 17:15:49 -0800709 // ----- Main service implementation -----
710
Christopher Tate487529a2009-04-29 14:03:25 -0700711 public BackupManagerService(Context context) {
712 mContext = context;
713 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700714 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700715 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700716
Christopher Tateb6787f22009-07-02 17:40:45 -0700717 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
718 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700719 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700720
Christopher Tate44a27902010-01-27 17:15:49 -0800721 mBackupManagerBinder = asInterface(asBinder());
722
723 // spin up the backup/restore handler thread
724 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
725 mHandlerThread.start();
726 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
727
Christopher Tate22b87872009-05-04 16:41:53 -0700728 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700729 final ContentResolver resolver = context.getContentResolver();
730 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700731 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700732 mProvisioned = Settings.Global.getInt(resolver,
733 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700734 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800735 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700736
737 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
738 resolver.registerContentObserver(
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700739 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
Christopher Tate97ea1222012-05-17 14:59:41 -0700740 false, mProvisionedObserver);
741
Oscar Montemayora8529f62009-11-18 10:14:20 -0800742 // If Encrypted file systems is enabled or disabled, this call will return the
743 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600744 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800745 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700746 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700747
Christopher Tate2efd2db2011-07-19 16:32:49 -0700748 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
749 if (mPasswordHashFile.exists()) {
750 FileInputStream fin = null;
751 DataInputStream in = null;
752 try {
753 fin = new FileInputStream(mPasswordHashFile);
754 in = new DataInputStream(new BufferedInputStream(fin));
755 // integer length of the salt array, followed by the salt,
756 // then the hex pw hash string
757 int saltLen = in.readInt();
758 byte[] salt = new byte[saltLen];
759 in.readFully(salt);
760 mPasswordHash = in.readUTF();
761 mPasswordSalt = salt;
762 } catch (IOException e) {
763 Slog.e(TAG, "Unable to read saved backup pw hash");
764 } finally {
765 try {
766 if (in != null) in.close();
767 if (fin != null) fin.close();
768 } catch (IOException e) {
769 Slog.w(TAG, "Unable to close streams");
770 }
771 }
772 }
773
Christopher Tate4cc86e12009-09-21 19:36:51 -0700774 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700775 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700776 IntentFilter filter = new IntentFilter();
777 filter.addAction(RUN_BACKUP_ACTION);
778 context.registerReceiver(mRunBackupReceiver, filter,
779 android.Manifest.permission.BACKUP, null);
780
781 mRunInitReceiver = new RunInitializeReceiver();
782 filter = new IntentFilter();
783 filter.addAction(RUN_INITIALIZE_ACTION);
784 context.registerReceiver(mRunInitReceiver, filter,
785 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700786
787 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700788 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
789 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
790
Christopher Tate4cc86e12009-09-21 19:36:51 -0700791 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
792 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
793 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
794
Christopher Tatecde87f42009-06-12 12:55:53 -0700795 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700796 mJournalDir = new File(mBaseStateDir, "pending");
797 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700798 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700799
Christopher Tate73e02522009-07-15 14:18:26 -0700800 // Set up the various sorts of package tracking we do
801 initPackageTracking();
802
Christopher Tateabce4e82009-06-18 18:35:32 -0700803 // Build our mapping of uid to backup client services. This implicitly
804 // schedules a backup pass on the Package Manager metadata the first
805 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700806 synchronized (mBackupParticipants) {
807 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700808 }
809
Dan Egnor87a02bc2009-06-17 02:30:10 -0700810 // Set up our transport options and initialize the default transport
811 // TODO: Have transports register themselves somehow?
812 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700813 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700814 ComponentName localName = new ComponentName(context, LocalTransport.class);
815 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700816
Christopher Tate91717492009-06-26 21:07:13 -0700817 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700818 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
819 Settings.Secure.BACKUP_TRANSPORT);
820 if ("".equals(mCurrentTransport)) {
821 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700822 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700824
825 // Attach to the Google backup transport. When this comes up, it will set
826 // itself as the current transport because we explicitly reset mCurrentTransport
827 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700828 ComponentName transportComponent = new ComponentName("com.google.android.backup",
829 "com.google.android.backup.BackupTransportService");
830 try {
831 // If there's something out there that is supposed to be the Google
832 // backup transport, make sure it's legitimately part of the OS build
833 // and not an app lying about its package name.
834 ApplicationInfo info = mPackageManager.getApplicationInfo(
835 transportComponent.getPackageName(), 0);
836 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
837 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
838 Intent intent = new Intent().setComponent(transportComponent);
839 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
840 } else {
841 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
842 }
843 } catch (PackageManager.NameNotFoundException nnf) {
844 // No such package? No binding.
845 if (DEBUG) Slog.v(TAG, "Google transport not present");
846 }
Christopher Tateaa088442009-06-16 18:25:46 -0700847
Christopher Tatecde87f42009-06-12 12:55:53 -0700848 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700849 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700850 parseLeftoverJournals();
851
Christopher Tateb6787f22009-07-02 17:40:45 -0700852 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700853 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700854
855 // Start the backup passes going
856 setBackupEnabled(areEnabled);
857 }
858
859 private class RunBackupReceiver extends BroadcastReceiver {
860 public void onReceive(Context context, Intent intent) {
861 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700862 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700863 if (mPendingInits.size() > 0) {
864 // If there are pending init operations, we process those
865 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700867 try {
868 mAlarmManager.cancel(mRunInitIntent);
869 mRunInitIntent.send();
870 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700872 // can't really do more than bail here
873 }
874 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800875 // Don't run backups now if we're disabled or not yet
876 // fully set up.
877 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700878 if (!mBackupRunning) {
879 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700880
Christopher Tate336a6492011-10-05 16:05:43 -0700881 // Acquire the wakelock and pass it to the backup thread. it will
882 // be released once backup concludes.
883 mBackupRunning = true;
884 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700885
Christopher Tate336a6492011-10-05 16:05:43 -0700886 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
887 mBackupHandler.sendMessage(msg);
888 } else {
889 Slog.i(TAG, "Backup time but one already running");
890 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700891 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800892 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700893 }
894 }
895 }
896 }
897 }
898 }
899
900 private class RunInitializeReceiver extends BroadcastReceiver {
901 public void onReceive(Context context, Intent intent) {
902 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
903 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700905
906 // Acquire the wakelock and pass it to the init thread. it will
907 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700908 mWakelock.acquire();
909
Christopher Tate4cc86e12009-09-21 19:36:51 -0700910 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700911 mBackupHandler.sendMessage(msg);
912 }
913 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700914 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700915 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700916
Christopher Tate73e02522009-07-15 14:18:26 -0700917 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700919
Christopher Tate84725812010-02-04 15:52:40 -0800920 // Remember our ancestral dataset
921 mTokenFile = new File(mBaseStateDir, "ancestral");
922 try {
923 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800924 int version = tf.readInt();
925 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
926 mAncestralToken = tf.readLong();
927 mCurrentToken = tf.readLong();
928
929 int numPackages = tf.readInt();
930 if (numPackages >= 0) {
931 mAncestralPackages = new HashSet<String>();
932 for (int i = 0; i < numPackages; i++) {
933 String pkgName = tf.readUTF();
934 mAncestralPackages.add(pkgName);
935 }
936 }
937 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800938 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800939 } catch (FileNotFoundException fnf) {
940 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800941 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800942 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800943 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800944 }
945
Christopher Tatee97e8072009-07-15 16:45:50 -0700946 // Keep a log of what apps we've ever backed up. Because we might have
947 // rebooted in the middle of an operation that was removing something from
948 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700949 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700950 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700951
Christopher Tatee97e8072009-07-15 16:45:50 -0700952 // If we were in the middle of removing something from the ever-backed-up
953 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700954 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700955 if (tempProcessedFile.exists()) {
956 tempProcessedFile.delete();
957 }
958
Dan Egnor852f8e42009-09-30 11:20:45 -0700959 // If there are previous contents, parse them out then start a new
960 // file to continue the recordkeeping.
961 if (mEverStored.exists()) {
962 RandomAccessFile temp = null;
963 RandomAccessFile in = null;
964
965 try {
966 temp = new RandomAccessFile(tempProcessedFile, "rws");
967 in = new RandomAccessFile(mEverStored, "r");
968
969 while (true) {
970 PackageInfo info;
971 String pkg = in.readUTF();
972 try {
973 info = mPackageManager.getPackageInfo(pkg, 0);
974 mEverStoredApps.add(pkg);
975 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700976 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700977 } catch (NameNotFoundException e) {
978 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700979 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700980 }
981 }
982 } catch (EOFException e) {
983 // Once we've rewritten the backup history log, atomically replace the
984 // old one with the new one then reopen the file for continuing use.
985 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700987 }
988 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700990 } finally {
991 try { if (temp != null) temp.close(); } catch (IOException e) {}
992 try { if (in != null) in.close(); } catch (IOException e) {}
993 }
994 }
995
Christopher Tate73e02522009-07-15 14:18:26 -0700996 // Register for broadcasts about package install, etc., so we can
997 // update the provider list.
998 IntentFilter filter = new IntentFilter();
999 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1000 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1001 filter.addDataScheme("package");
1002 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001003 // Register for events related to sdcard installation.
1004 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001005 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1006 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001007 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001008 }
1009
Christopher Tatecde87f42009-06-12 12:55:53 -07001010 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001011 for (File f : mJournalDir.listFiles()) {
1012 if (mJournal == null || f.compareTo(mJournal) != 0) {
1013 // This isn't the current journal, so it must be a leftover. Read
1014 // out the package names mentioned there and schedule them for
1015 // backup.
1016 RandomAccessFile in = null;
1017 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001018 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001019 in = new RandomAccessFile(f, "r");
1020 while (true) {
1021 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001022 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001023 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001024 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001025 } catch (EOFException e) {
1026 // no more data; we're done
1027 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001029 } finally {
1030 // close/delete the file
1031 try { if (in != null) in.close(); } catch (IOException e) {}
1032 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001033 }
1034 }
1035 }
1036 }
1037
Christopher Tate2efd2db2011-07-19 16:32:49 -07001038 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1039 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1040 }
1041
1042 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1043 try {
1044 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1045 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1046 return keyFactory.generateSecret(ks);
1047 } catch (InvalidKeySpecException e) {
1048 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1049 } catch (NoSuchAlgorithmException e) {
1050 Slog.e(TAG, "PBKDF2 unavailable!");
1051 }
1052 return null;
1053 }
1054
1055 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1056 SecretKey key = buildPasswordKey(pw, salt, rounds);
1057 if (key != null) {
1058 return byteArrayToHex(key.getEncoded());
1059 }
1060 return null;
1061 }
1062
1063 private String byteArrayToHex(byte[] data) {
1064 StringBuilder buf = new StringBuilder(data.length * 2);
1065 for (int i = 0; i < data.length; i++) {
1066 buf.append(Byte.toHexString(data[i], true));
1067 }
1068 return buf.toString();
1069 }
1070
1071 private byte[] hexToByteArray(String digits) {
1072 final int bytes = digits.length() / 2;
1073 if (2*bytes != digits.length()) {
1074 throw new IllegalArgumentException("Hex string must have an even number of digits");
1075 }
1076
1077 byte[] result = new byte[bytes];
1078 for (int i = 0; i < digits.length(); i += 2) {
1079 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1080 }
1081 return result;
1082 }
1083
1084 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1085 char[] mkAsChar = new char[pwBytes.length];
1086 for (int i = 0; i < pwBytes.length; i++) {
1087 mkAsChar[i] = (char) pwBytes[i];
1088 }
1089
1090 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1091 return checksum.getEncoded();
1092 }
1093
1094 // Used for generating random salts or passwords
1095 private byte[] randomBytes(int bits) {
1096 byte[] array = new byte[bits / 8];
1097 mRng.nextBytes(array);
1098 return array;
1099 }
1100
1101 // Backup password management
1102 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001103 // First, on an encrypted device we require matching the device pw
1104 final boolean isEncrypted;
1105 try {
1106 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1107 if (isEncrypted) {
1108 if (DEBUG) {
1109 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1110 }
1111 // 0 means the password validated
1112 // -2 means device not encrypted
1113 // Any other result is either password failure or an error condition,
1114 // so we refuse the match
1115 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1116 if (result == 0) {
1117 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1118 return true;
1119 } else if (result != -2) {
1120 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1121 return false;
1122 } else {
1123 // ...else the device is supposedly not encrypted. HOWEVER, the
1124 // query about the encryption state said that the device *is*
1125 // encrypted, so ... we may have a problem. Log it and refuse
1126 // the backup.
1127 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1128 return false;
1129 }
1130 }
1131 } catch (Exception e) {
1132 // Something went wrong talking to the mount service. This is very bad;
1133 // assume that we fail password validation.
1134 return false;
1135 }
1136
Christopher Tate2efd2db2011-07-19 16:32:49 -07001137 if (mPasswordHash == null) {
1138 // no current password case -- require that 'currentPw' be null or empty
1139 if (candidatePw == null || "".equals(candidatePw)) {
1140 return true;
1141 } // else the non-empty candidate does not match the empty stored pw
1142 } else {
1143 // hash the stated current pw and compare to the stored one
1144 if (candidatePw != null && candidatePw.length() > 0) {
1145 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1146 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1147 // candidate hash matches the stored hash -- the password matches
1148 return true;
1149 }
1150 } // else the stored pw is nonempty but the candidate is empty; no match
1151 }
1152 return false;
1153 }
1154
1155 @Override
1156 public boolean setBackupPassword(String currentPw, String newPw) {
1157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1158 "setBackupPassword");
1159
1160 // If the supplied pw doesn't hash to the the saved one, fail
1161 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1162 return false;
1163 }
1164
1165 // Clearing the password is okay
1166 if (newPw == null || newPw.isEmpty()) {
1167 if (mPasswordHashFile.exists()) {
1168 if (!mPasswordHashFile.delete()) {
1169 // Unable to delete the old pw file, so fail
1170 Slog.e(TAG, "Unable to clear backup password");
1171 return false;
1172 }
1173 }
1174 mPasswordHash = null;
1175 mPasswordSalt = null;
1176 return true;
1177 }
1178
1179 try {
1180 // Okay, build the hash of the new backup password
1181 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1182 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1183
1184 OutputStream pwf = null, buffer = null;
1185 DataOutputStream out = null;
1186 try {
1187 pwf = new FileOutputStream(mPasswordHashFile);
1188 buffer = new BufferedOutputStream(pwf);
1189 out = new DataOutputStream(buffer);
1190 // integer length of the salt array, followed by the salt,
1191 // then the hex pw hash string
1192 out.writeInt(salt.length);
1193 out.write(salt);
1194 out.writeUTF(newPwHash);
1195 out.flush();
1196 mPasswordHash = newPwHash;
1197 mPasswordSalt = salt;
1198 return true;
1199 } finally {
1200 if (out != null) out.close();
1201 if (buffer != null) buffer.close();
1202 if (pwf != null) pwf.close();
1203 }
1204 } catch (IOException e) {
1205 Slog.e(TAG, "Unable to set backup password");
1206 }
1207 return false;
1208 }
1209
1210 @Override
1211 public boolean hasBackupPassword() {
1212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1213 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001214
1215 try {
1216 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1217 || (mPasswordHash != null && mPasswordHash.length() > 0);
1218 } catch (Exception e) {
1219 // If we can't talk to the mount service we have a serious problem; fail
1220 // "secure" i.e. assuming that we require a password
1221 return true;
1222 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001223 }
1224
Christopher Tate4cc86e12009-09-21 19:36:51 -07001225 // Maintain persistent state around whether need to do an initialize operation.
1226 // Must be called with the queue lock held.
1227 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001228 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001229 + " on transport " + transportName);
1230 try {
1231 IBackupTransport transport = getTransport(transportName);
1232 String transportDirName = transport.transportDirName();
1233 File stateDir = new File(mBaseStateDir, transportDirName);
1234 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1235
1236 if (isPending) {
1237 // We need an init before we can proceed with sending backup data.
1238 // Record that with an entry in our set of pending inits, as well as
1239 // journaling it via creation of a sentinel file.
1240 mPendingInits.add(transportName);
1241 try {
1242 (new FileOutputStream(initPendingFile)).close();
1243 } catch (IOException ioe) {
1244 // Something is badly wrong with our permissions; just try to move on
1245 }
1246 } else {
1247 // No more initialization needed; wipe the journal and reset our state.
1248 initPendingFile.delete();
1249 mPendingInits.remove(transportName);
1250 }
1251 } catch (RemoteException e) {
1252 // can't happen; the transport is local
1253 }
1254 }
1255
Christopher Tated55e18a2009-09-21 10:12:59 -07001256 // Reset all of our bookkeeping, in response to having been told that
1257 // the backend data has been wiped [due to idle expiry, for example],
1258 // so we must re-upload all saved settings.
1259 void resetBackupState(File stateFileDir) {
1260 synchronized (mQueueLock) {
1261 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001262 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001263 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001264
Christopher Tate84725812010-02-04 15:52:40 -08001265 mCurrentToken = 0;
1266 writeRestoreTokens();
1267
Christopher Tated55e18a2009-09-21 10:12:59 -07001268 // Remove all the state files
1269 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001270 // ... but don't touch the needs-init sentinel
1271 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1272 sf.delete();
1273 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001274 }
Christopher Tate45597642011-04-04 16:59:21 -07001275 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001276
Christopher Tate45597642011-04-04 16:59:21 -07001277 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001278 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001279 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001280 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001281 HashSet<String> participants = mBackupParticipants.valueAt(i);
1282 if (participants != null) {
1283 for (String packageName : participants) {
1284 dataChangedImpl(packageName);
1285 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001286 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001287 }
1288 }
1289 }
1290
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001291 // Add a transport to our set of available backends. If 'transport' is null, this
1292 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001293 private void registerTransport(String name, IBackupTransport transport) {
1294 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001296 if (transport != null) {
1297 mTransports.put(name, transport);
1298 } else {
1299 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001300 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001301 mCurrentTransport = null;
1302 }
1303 // Nothing further to do in the unregistration case
1304 return;
1305 }
Christopher Tate91717492009-06-26 21:07:13 -07001306 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001307
1308 // If the init sentinel file exists, we need to be sure to perform the init
1309 // as soon as practical. We also create the state directory at registration
1310 // time to ensure it's present from the outset.
1311 try {
1312 String transportName = transport.transportDirName();
1313 File stateDir = new File(mBaseStateDir, transportName);
1314 stateDir.mkdirs();
1315
1316 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1317 if (initSentinel.exists()) {
1318 synchronized (mQueueLock) {
1319 mPendingInits.add(transportName);
1320
1321 // TODO: pick a better starting time than now + 1 minute
1322 long delay = 1000 * 60; // one minute, in milliseconds
1323 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1324 System.currentTimeMillis() + delay, mRunInitIntent);
1325 }
1326 }
1327 } catch (RemoteException e) {
1328 // can't happen, the transport is local
1329 }
Christopher Tate91717492009-06-26 21:07:13 -07001330 }
1331
Christopher Tate3799bc22009-05-06 16:13:56 -07001332 // ----- Track installation/removal of packages -----
1333 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1334 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001335 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001336
Christopher Tate3799bc22009-05-06 16:13:56 -07001337 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001338 boolean replacing = false;
1339 boolean added = false;
1340 Bundle extras = intent.getExtras();
1341 String pkgList[] = null;
1342 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001343 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001344 Uri uri = intent.getData();
1345 if (uri == null) {
1346 return;
1347 }
1348 String pkgName = uri.getSchemeSpecificPart();
1349 if (pkgName != null) {
1350 pkgList = new String[] { pkgName };
1351 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001352 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1353 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001354 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001355 added = true;
1356 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001357 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001358 added = false;
1359 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1360 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001361
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001362 if (pkgList == null || pkgList.length == 0) {
1363 return;
1364 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001365
1366 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001367 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001368 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001369 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001370 // This is the package-replaced case; we just remove the entry
1371 // under the old uid and fall through to re-add.
1372 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001373 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001374 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001376 } else {
1377 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001378 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1379 } else {
1380 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001381 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001382 }
1383 }
1384 }
1385 }
1386 };
1387
Dan Egnor87a02bc2009-06-17 02:30:10 -07001388 // ----- Track connection to GoogleBackupTransport service -----
1389 ServiceConnection mGoogleConnection = new ServiceConnection() {
1390 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001391 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001392 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001393 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001394 }
1395
1396 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001398 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001399 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001400 }
1401 };
1402
Christopher Tate0bacfd22012-01-11 14:41:19 -08001403 // Add the backup agents in the given packages to our set of known backup participants.
1404 // If 'packageNames' is null, adds all backup agents in the whole system.
1405 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001406 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001407 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001408 if (packageNames != null) {
1409 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1410 for (String packageName : packageNames) {
1411 addPackageParticipantsLockedInner(packageName, targetApps);
1412 }
1413 } else {
1414 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1415 addPackageParticipantsLockedInner(null, targetApps);
1416 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001417 }
1418
Christopher Tate181fafa2009-05-14 11:12:14 -07001419 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001420 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001421 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001422 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001423 }
1424
Dan Egnorefe52642009-06-24 00:16:33 -07001425 for (PackageInfo pkg : targetPkgs) {
1426 if (packageName == null || pkg.packageName.equals(packageName)) {
1427 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001428 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001429 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001430 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001431 mBackupParticipants.put(uid, set);
1432 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001433 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001434 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001435
1436 // If we've never seen this app before, schedule a backup for it
1437 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001438 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001439 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001440 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001441 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001442 }
Christopher Tate487529a2009-04-29 14:03:25 -07001443 }
1444 }
1445
Christopher Tate0bacfd22012-01-11 14:41:19 -08001446 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001447 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001448 if (packageNames == null) {
1449 Slog.w(TAG, "removePackageParticipants with null list");
1450 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001451 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001452
Christopher Tatea3d55342012-03-27 13:16:18 -07001453 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1454 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001455 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001456 // Known previous UID, so we know which package set to check
1457 HashSet<String> set = mBackupParticipants.get(oldUid);
1458 if (set != null && set.contains(pkg)) {
1459 removePackageFromSetLocked(set, pkg);
1460 if (set.isEmpty()) {
1461 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1462 mBackupParticipants.remove(oldUid);
1463 }
1464 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001465 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001466 }
1467
Christopher Tatea3d55342012-03-27 13:16:18 -07001468 private void removePackageFromSetLocked(final HashSet<String> set,
1469 final String packageName) {
1470 if (set.contains(packageName)) {
1471 // Found it. Remove this one package from the bookkeeping, and
1472 // if it's the last participating app under this uid we drop the
1473 // (now-empty) set as well.
1474 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
1475 removeEverBackedUp(packageName);
1476 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001477 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001478 }
1479 }
1480
Christopher Tate181fafa2009-05-14 11:12:14 -07001481 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001482 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001483 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001484 int flags = PackageManager.GET_SIGNATURES;
1485 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1486 int N = packages.size();
1487 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001488 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001489 try {
1490 ApplicationInfo app = pkg.applicationInfo;
1491 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001492 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001493 packages.remove(a);
1494 }
1495 else {
1496 // we will need the shared library path, so look that up and store it here
1497 app = mPackageManager.getApplicationInfo(pkg.packageName,
1498 PackageManager.GET_SHARED_LIBRARY_FILES);
1499 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1500 }
1501 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001502 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001503 }
1504 }
Dan Egnorefe52642009-06-24 00:16:33 -07001505 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001506 }
Christopher Tateaa088442009-06-16 18:25:46 -07001507
Christopher Tate84725812010-02-04 15:52:40 -08001508 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001509 // backed up at least once
1510 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001511 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1512
1513 synchronized (mEverStoredApps) {
1514 if (!mEverStoredApps.add(packageName)) return;
1515
1516 RandomAccessFile out = null;
1517 try {
1518 out = new RandomAccessFile(mEverStored, "rws");
1519 out.seek(out.length());
1520 out.writeUTF(packageName);
1521 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001523 } finally {
1524 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001525 }
1526 }
1527 }
1528
Christopher Tatee97e8072009-07-15 16:45:50 -07001529 // Remove our awareness of having ever backed up the given package
1530 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001531 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1532 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001533
Dan Egnor852f8e42009-09-30 11:20:45 -07001534 synchronized (mEverStoredApps) {
1535 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1536 // we'll recognize on initialization time that the package no longer
1537 // exists and fix it up then.
1538 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1539 RandomAccessFile known = null;
1540 try {
1541 known = new RandomAccessFile(tempKnownFile, "rws");
1542 mEverStoredApps.remove(packageName);
1543 for (String s : mEverStoredApps) {
1544 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001545 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001546 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001547 known.close();
1548 known = null;
1549 if (!tempKnownFile.renameTo(mEverStored)) {
1550 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1551 }
1552 } catch (IOException e) {
1553 // Bad: we couldn't create the new copy. For safety's sake we
1554 // abandon the whole process and remove all what's-backed-up
1555 // state entirely, meaning we'll force a backup pass for every
1556 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001558 mEverStoredApps.clear();
1559 tempKnownFile.delete();
1560 mEverStored.delete();
1561 } finally {
1562 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001563 }
1564 }
1565 }
1566
Christopher Tateb49ceb32010-02-08 16:22:24 -08001567 // Persistently record the current and ancestral backup tokens as well
1568 // as the set of packages with data [supposedly] available in the
1569 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001570 void writeRestoreTokens() {
1571 try {
1572 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001573
1574 // First, the version number of this record, for futureproofing
1575 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1576
1577 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001578 af.writeLong(mAncestralToken);
1579 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001580
1581 // Now write the set of ancestral packages
1582 if (mAncestralPackages == null) {
1583 af.writeInt(-1);
1584 } else {
1585 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001587 for (String pkgName : mAncestralPackages) {
1588 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001589 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001590 }
1591 }
Christopher Tate84725812010-02-04 15:52:40 -08001592 af.close();
1593 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001595 }
1596 }
1597
Dan Egnor87a02bc2009-06-17 02:30:10 -07001598 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001599 private IBackupTransport getTransport(String transportName) {
1600 synchronized (mTransports) {
1601 IBackupTransport transport = mTransports.get(transportName);
1602 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001603 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001604 }
1605 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001606 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001607 }
1608
Christopher Tatedf01dea2009-06-09 20:45:02 -07001609 // fire off a backup agent, blocking until it attaches or times out
1610 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1611 IBackupAgent agent = null;
1612 synchronized(mAgentConnectLock) {
1613 mConnecting = true;
1614 mConnectedAgent = null;
1615 try {
1616 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001618
1619 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001620 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001621 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1622 while (mConnecting && mConnectedAgent == null
1623 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001624 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001626 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001627 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001628 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001629 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001630 return null;
1631 }
1632 }
1633
1634 // if we timed out with no connect, abort and move on
1635 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001637 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 return null;
1639 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001640 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001641 agent = mConnectedAgent;
1642 }
1643 } catch (RemoteException e) {
1644 // can't happen
1645 }
1646 }
1647 return agent;
1648 }
1649
Christopher Tatec7b31e32009-06-10 15:49:30 -07001650 // clear an application's data, blocking until the operation completes or times out
1651 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001652 // Don't wipe packages marked allowClearUserData=false
1653 try {
1654 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1655 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001656 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001657 + packageName);
1658 return;
1659 }
1660 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001662 return;
1663 }
1664
Christopher Tatec7b31e32009-06-10 15:49:30 -07001665 ClearDataObserver observer = new ClearDataObserver();
1666
1667 synchronized(mClearDataLock) {
1668 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001669 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001670 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001671 } catch (RemoteException e) {
1672 // can't happen because the activity manager is in this process
1673 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001674
1675 // only wait 10 seconds for the clear data to happen
1676 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1677 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1678 try {
1679 mClearDataLock.wait(5000);
1680 } catch (InterruptedException e) {
1681 // won't happen, but still.
1682 mClearingData = false;
1683 }
1684 }
1685 }
1686 }
1687
1688 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001689 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001690 synchronized(mClearDataLock) {
1691 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001692 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001693 }
1694 }
1695 }
1696
Christopher Tate1bb69062010-02-19 17:02:12 -08001697 // Get the restore-set token for the best-available restore set for this package:
1698 // the active set if possible, else the ancestral one. Returns zero if none available.
1699 long getAvailableRestoreToken(String packageName) {
1700 long token = mAncestralToken;
1701 synchronized (mQueueLock) {
1702 if (mEverStoredApps.contains(packageName)) {
1703 token = mCurrentToken;
1704 }
1705 }
1706 return token;
1707 }
1708
Christopher Tate44a27902010-01-27 17:15:49 -08001709 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001710 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1711
1712 interface BackupRestoreTask {
1713 // Execute one tick of whatever state machine the task implements
1714 void execute();
1715
1716 // An operation that wanted a callback has completed
1717 void operationComplete();
1718
1719 // An operation that wanted a callback has timed out
1720 void handleTimeout();
1721 }
1722
1723 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1724 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1725 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001726 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001727 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1728
1729 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1730 mBackupHandler.sendMessageDelayed(msg, interval);
1731 }
1732 }
1733
1734 // synchronous waiter case
1735 boolean waitUntilOperationComplete(int token) {
1736 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1737 + Integer.toHexString(token));
1738 int finalState = OP_PENDING;
1739 Operation op = null;
1740 synchronized (mCurrentOpLock) {
1741 while (true) {
1742 op = mCurrentOperations.get(token);
1743 if (op == null) {
1744 // mysterious disappearance: treat as success with no callback
1745 break;
1746 } else {
1747 if (op.state == OP_PENDING) {
1748 try {
1749 mCurrentOpLock.wait();
1750 } catch (InterruptedException e) {}
1751 // When the wait is notified we loop around and recheck the current state
1752 } else {
1753 // No longer pending; we're done
1754 finalState = op.state;
1755 break;
1756 }
Christopher Tate44a27902010-01-27 17:15:49 -08001757 }
Christopher Tate44a27902010-01-27 17:15:49 -08001758 }
1759 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001760
Christopher Tate44a27902010-01-27 17:15:49 -08001761 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001762 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001763 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001764 return finalState == OP_ACKNOWLEDGED;
1765 }
1766
Christopher Tate8e294d42011-08-31 20:37:12 -07001767 void handleTimeout(int token, Object obj) {
1768 // Notify any synchronous waiters
1769 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001770 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001771 op = mCurrentOperations.get(token);
1772 if (MORE_DEBUG) {
1773 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1774 + " but no op found");
1775 }
1776 int state = (op != null) ? op.state : OP_TIMEOUT;
1777 if (state == OP_PENDING) {
1778 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1779 op.state = OP_TIMEOUT;
1780 mCurrentOperations.put(token, op);
1781 }
1782 mCurrentOpLock.notifyAll();
1783 }
1784
1785 // If there's a TimeoutHandler for this event, call it
1786 if (op != null && op.callback != null) {
1787 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001788 }
Christopher Tate44a27902010-01-27 17:15:49 -08001789 }
1790
Christopher Tate043dadc2009-06-02 16:11:00 -07001791 // ----- Back up a set of applications via a worker thread -----
1792
Christopher Tate8e294d42011-08-31 20:37:12 -07001793 enum BackupState {
1794 INITIAL,
1795 RUNNING_QUEUE,
1796 FINAL
1797 }
1798
1799 class PerformBackupTask implements BackupRestoreTask {
1800 private static final String TAG = "PerformBackupTask";
1801
Christopher Tateaa088442009-06-16 18:25:46 -07001802 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001803 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001804 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001805 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001806 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001807 BackupState mCurrentState;
1808
1809 // carried information about the current in-flight operation
1810 PackageInfo mCurrentPackage;
1811 File mSavedStateName;
1812 File mBackupDataName;
1813 File mNewStateName;
1814 ParcelFileDescriptor mSavedState;
1815 ParcelFileDescriptor mBackupData;
1816 ParcelFileDescriptor mNewState;
1817 int mStatus;
1818 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001819
Christopher Tate44a27902010-01-27 17:15:49 -08001820 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001821 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001822 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001823 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001824 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001825
1826 try {
1827 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1828 } catch (RemoteException e) {
1829 // can't happen; the transport is local
1830 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001831
1832 mCurrentState = BackupState.INITIAL;
1833 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001834
1835 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001836 }
1837
Christopher Tate8e294d42011-08-31 20:37:12 -07001838 // Main entry point: perform one chunk of work, updating the state as appropriate
1839 // and reposting the next chunk to the primary backup handler thread.
1840 @Override
1841 public void execute() {
1842 switch (mCurrentState) {
1843 case INITIAL:
1844 beginBackup();
1845 break;
1846
1847 case RUNNING_QUEUE:
1848 invokeNextAgent();
1849 break;
1850
1851 case FINAL:
1852 if (!mFinished) finalizeBackup();
1853 else {
1854 Slog.e(TAG, "Duplicate finish");
1855 }
Christopher Tate2982d062011-09-06 20:35:24 -07001856 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001857 break;
1858 }
1859 }
1860
1861 // We're starting a backup pass. Initialize the transport and send
1862 // the PM metadata blob if we haven't already.
1863 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001864 if (DEBUG_BACKUP_TRACE) {
1865 clearBackupTrace();
1866 StringBuilder b = new StringBuilder(256);
1867 b.append("beginBackup: [");
1868 for (BackupRequest req : mOriginalQueue) {
1869 b.append(' ');
1870 b.append(req.packageName);
1871 }
1872 b.append(" ]");
1873 addBackupTrace(b.toString());
1874 }
1875
Christopher Tate8e294d42011-08-31 20:37:12 -07001876 mStatus = BackupConstants.TRANSPORT_OK;
1877
1878 // Sanity check: if the queue is empty we have no work to do.
1879 if (mOriginalQueue.isEmpty()) {
1880 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001881 addBackupTrace("queue empty at begin");
1882 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001883 return;
1884 }
1885
1886 // We need to retain the original queue contents in case of transport
1887 // failure, but we want a working copy that we can manipulate along
1888 // the way.
1889 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1890
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001892
Christopher Tate8e294d42011-08-31 20:37:12 -07001893 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001894 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001895 final String transportName = mTransport.transportDirName();
1896 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001897
Dan Egnor852f8e42009-09-30 11:20:45 -07001898 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001899 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001901 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001902 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001904
1905 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001906 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001907 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001908 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001909 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001910 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001911 }
Dan Egnor01445162009-09-21 17:04:05 -07001912 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001913
1914 // The package manager doesn't have a proper <application> etc, but since
1915 // it's running here in the system process we can just set up its agent
1916 // directly and use a synthetic BackupRequest. We always run this pass
1917 // because it's cheap and this way we guarantee that we don't get out of
1918 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001919 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001920 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1921 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001922 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001923 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001924 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001925 }
Christopher Tate90967f42009-09-20 15:28:33 -07001926
Christopher Tate8e294d42011-08-31 20:37:12 -07001927 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1928 // The backend reports that our dataset has been wiped. Note this in
1929 // the event log; the no-success code below will reset the backup
1930 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001931 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001932 }
1933 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001934 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001935 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001936 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001937 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001938 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1939 // metadata and its completion/timeout callback will continue the state
1940 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001941 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001942 if (mStatus != BackupConstants.TRANSPORT_OK) {
1943 // if things went wrong at this point, we need to
1944 // restage everything and try again later.
1945 resetBackupState(mStateDir); // Just to make sure.
1946 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001947 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001948 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001949 }
1950
Christopher Tate8e294d42011-08-31 20:37:12 -07001951 // Transport has been initialized and the PM metadata submitted successfully
1952 // if that was warranted. Now we process the single next thing in the queue.
1953 void invokeNextAgent() {
1954 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001955 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001956
Christopher Tate8e294d42011-08-31 20:37:12 -07001957 // Sanity check that we have work to do. If not, skip to the end where
1958 // we reestablish the wakelock invariants etc.
1959 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001960 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001961 executeNextState(BackupState.FINAL);
1962 return;
1963 }
1964
1965 // pop the entry we're going to process on this step
1966 BackupRequest request = mQueue.get(0);
1967 mQueue.remove(0);
1968
1969 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001970 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001971
1972 // Verify that the requested app exists; it might be something that
1973 // requested a backup but was then uninstalled. The request was
1974 // journalled and rather than tamper with the journal it's safer
1975 // to sanity-check here. This also gives us the classname of the
1976 // package's backup agent.
1977 try {
1978 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1979 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001980 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1981 // The manifest has changed but we had a stale backup request pending.
1982 // This won't happen again because the app won't be requesting further
1983 // backups.
1984 Slog.i(TAG, "Package " + request.packageName
1985 + " no longer supports backup; skipping");
1986 addBackupTrace("skipping - no agent, completion is noop");
1987 executeNextState(BackupState.RUNNING_QUEUE);
1988 return;
1989 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001990
Christopher Tate043dadc2009-06-02 16:11:00 -07001991 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001992 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001993 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1994 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001995 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001996 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001997 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001998 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1999 // at this point we'll either get a completion callback from the
2000 // agent, or a timeout message on the main handler. either way, we're
2001 // done here as long as we're successful so far.
2002 } else {
2003 // Timeout waiting for the agent
2004 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002005 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002006 } catch (SecurityException ex) {
2007 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002008 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002009 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002010 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002011 }
2012 } catch (NameNotFoundException e) {
2013 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002014 addBackupTrace("no such package");
2015 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002016 } finally {
2017 mWakelock.setWorkSource(null);
2018
2019 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002020 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002021 if (mStatus != BackupConstants.TRANSPORT_OK) {
2022 BackupState nextState = BackupState.RUNNING_QUEUE;
2023
2024 // An agent-level failure means we reenqueue this one agent for
2025 // a later retry, but otherwise proceed normally.
2026 if (mStatus == BackupConstants.AGENT_ERROR) {
2027 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2028 + " - restaging");
2029 dataChangedImpl(request.packageName);
2030 mStatus = BackupConstants.TRANSPORT_OK;
2031 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002032 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2033 // Failed lookup of the app, so we couldn't bring up an agent, but
2034 // we're otherwise fine. Just drop it and go on to the next as usual.
2035 mStatus = BackupConstants.TRANSPORT_OK;
2036 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002037 // Transport-level failure means we reenqueue everything
2038 revertAndEndBackup();
2039 nextState = BackupState.FINAL;
2040 }
2041
2042 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002043 } else {
2044 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002045 }
2046 }
2047 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002048
Christopher Tate8e294d42011-08-31 20:37:12 -07002049 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002050 addBackupTrace("finishing");
2051
Christopher Tate8e294d42011-08-31 20:37:12 -07002052 // Either backup was successful, in which case we of course do not need
2053 // this pass's journal any more; or it failed, in which case we just
2054 // re-enqueued all of these packages in the current active journal.
2055 // Either way, we no longer need this pass's journal.
2056 if (mJournal != null && !mJournal.delete()) {
2057 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2058 }
2059
2060 // If everything actually went through and this is the first time we've
2061 // done a backup, we can now record what the current backup dataset token
2062 // is.
2063 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002064 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 try {
2066 mCurrentToken = mTransport.getCurrentRestoreSet();
2067 } catch (RemoteException e) {} // can't happen
2068 writeRestoreTokens();
2069 }
2070
Christopher Tate336a6492011-10-05 16:05:43 -07002071 // Set up the next backup pass - at this point we can set mBackupRunning
2072 // to false to allow another pass to fire, because we're done with the
2073 // state machine sequence and the wakelock is refcounted.
2074 synchronized (mQueueLock) {
2075 mBackupRunning = false;
2076 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002077 // Make sure we back up everything and perform the one-time init
2078 clearMetadata();
2079 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002080 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002081 backupNow();
2082 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002083 }
2084
2085 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002086 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002087 Slog.i(TAG, "Backup pass finished.");
2088 mWakelock.release();
2089 }
2090
Christopher Tatee659fb92011-10-10 16:34:50 -07002091 // Remove the PM metadata state. This will generate an init on the next pass.
2092 void clearMetadata() {
2093 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2094 if (pmState.exists()) pmState.delete();
2095 }
2096
Christopher Tate8e294d42011-08-31 20:37:12 -07002097 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2098 // handler in case it doesn't get back to us.
2099 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002100 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002101 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2102 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002103
Christopher Tate8e294d42011-08-31 20:37:12 -07002104 mSavedStateName = new File(mStateDir, packageName);
2105 mBackupDataName = new File(mDataDir, packageName + ".data");
2106 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002107
Christopher Tate8e294d42011-08-31 20:37:12 -07002108 mSavedState = null;
2109 mBackupData = null;
2110 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111
Christopher Tate4a627c72011-04-01 14:43:32 -07002112 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002113 try {
2114 // Look up the package info & signatures. This is first so that if it
2115 // throws an exception, there's no file setup yet that would need to
2116 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002117 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002118 // The metadata 'package' is synthetic; construct one and make
2119 // sure our global state is pointed at it
2120 mCurrentPackage = new PackageInfo();
2121 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002122 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002123
Christopher Tatec7b31e32009-06-10 15:49:30 -07002124 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002125 // the saved-state "file". This is by definition an incremental,
2126 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002127 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002128 ParcelFileDescriptor.MODE_READ_ONLY |
2129 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002130
Christopher Tate8e294d42011-08-31 20:37:12 -07002131 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002132 ParcelFileDescriptor.MODE_READ_WRITE |
2133 ParcelFileDescriptor.MODE_CREATE |
2134 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002135
Christopher Tate8e294d42011-08-31 20:37:12 -07002136 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002137 ParcelFileDescriptor.MODE_READ_WRITE |
2138 ParcelFileDescriptor.MODE_CREATE |
2139 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002140
Christopher Tate44a27902010-01-27 17:15:49 -08002141 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002142 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002143 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002144 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002145 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002146 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002147 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002148 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002149 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2150 e.toString());
2151 agentErrorCleanup();
2152 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002153 }
2154
Christopher Tate8e294d42011-08-31 20:37:12 -07002155 // At this point the agent is off and running. The next thing to happen will
2156 // either be a callback from the agent, at which point we'll process its data
2157 // for transport, or a timeout. Either way the next phase will happen in
2158 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002159 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002160 return BackupConstants.TRANSPORT_OK;
2161 }
2162
2163 @Override
2164 public void operationComplete() {
2165 // Okay, the agent successfully reported back to us. Spin the data off to the
2166 // transport and proceed with the next stage.
2167 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2168 + mCurrentPackage.packageName);
2169 mBackupHandler.removeMessages(MSG_TIMEOUT);
2170 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002171 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002172
2173 ParcelFileDescriptor backupData = null;
2174 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002175 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002176 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002177 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002178 if (mStatus == BackupConstants.TRANSPORT_OK) {
2179 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002180 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002181 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002182 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002183 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002184
Dan Egnor83861e72009-09-17 16:17:55 -07002185 // TODO - We call finishBackup() for each application backed up, because
2186 // we need to know now whether it succeeded or failed. Instead, we should
2187 // hold off on finishBackup() until the end, which implies holding off on
2188 // renaming *all* the output state files (see below) until that happens.
2189
Christopher Tate6de74ff2012-01-17 15:20:32 -08002190 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002191 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002192 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002193 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002194 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002195 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002196 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002197 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002198 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002199 }
2200
2201 // After successful transport, delete the now-stale data
2202 // and juggle the files so that next time we supply the agent
2203 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002204 if (mStatus == BackupConstants.TRANSPORT_OK) {
2205 mBackupDataName.delete();
2206 mNewStateName.renameTo(mSavedStateName);
2207 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2208 mCurrentPackage.packageName, size);
2209 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002210 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002211 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2212 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002213 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002214 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002215 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2216 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2217 mCurrentPackage.packageName);
2218 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002219 } finally {
2220 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002221 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002222
Christopher Tate8e294d42011-08-31 20:37:12 -07002223 // If we encountered an error here it's a transport-level failure. That
2224 // means we need to halt everything and reschedule everything for next time.
2225 final BackupState nextState;
2226 if (mStatus != BackupConstants.TRANSPORT_OK) {
2227 revertAndEndBackup();
2228 nextState = BackupState.FINAL;
2229 } else {
2230 // Success! Proceed with the next app if any, otherwise we're done.
2231 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2232 }
2233
2234 executeNextState(nextState);
2235 }
2236
2237 @Override
2238 public void handleTimeout() {
2239 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2240 // it for the next time we run a backup pass.
2241 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2242 // fail repeatedly (i.e. have proved themselves to be buggy).
2243 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2244 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2245 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002246 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002247 agentErrorCleanup();
2248 dataChangedImpl(mCurrentPackage.packageName);
2249 }
2250
2251 void revertAndEndBackup() {
2252 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002253 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002254 for (BackupRequest request : mOriginalQueue) {
2255 dataChangedImpl(request.packageName);
2256 }
2257 // We also want to reset the backup schedule based on whatever
2258 // the transport suggests by way of retry/backoff time.
2259 restartBackupAlarm();
2260 }
2261
2262 void agentErrorCleanup() {
2263 mBackupDataName.delete();
2264 mNewStateName.delete();
2265 clearAgentState();
2266
2267 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2268 }
2269
2270 // Cleanup common to both success and failure cases
2271 void clearAgentState() {
2272 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2273 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2274 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2275 mSavedState = mBackupData = mNewState = null;
2276 synchronized (mCurrentOpLock) {
2277 mCurrentOperations.clear();
2278 }
2279
2280 // If this was a pseudopackage there's no associated Activity Manager state
2281 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002282 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002283 try { // unbind even on timeout, just in case
2284 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2285 } catch (RemoteException e) {}
2286 }
2287 }
2288
2289 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002290 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002291 synchronized (mQueueLock) {
2292 try {
2293 startBackupAlarmsLocked(mTransport.requestBackupTime());
2294 } catch (RemoteException e) { /* cannot happen */ }
2295 }
2296 }
2297
2298 void executeNextState(BackupState nextState) {
2299 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2300 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002301 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002302 mCurrentState = nextState;
2303 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2304 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002305 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002306 }
2307
Christopher Tatedf01dea2009-06-09 20:45:02 -07002308
Christopher Tate4a627c72011-04-01 14:43:32 -07002309 // ----- Full backup to a file/socket -----
2310
2311 class PerformFullBackupTask implements Runnable {
2312 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002313 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002314 IFullBackupRestoreObserver mObserver;
2315 boolean mIncludeApks;
2316 boolean mIncludeShared;
2317 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002318 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002319 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002320 String mCurrentPassword;
2321 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002322 AtomicBoolean mLatchObject;
2323 File mFilesDir;
2324 File mManifestFile;
2325
Christopher Tate7926a692011-07-11 11:31:57 -07002326 class FullBackupRunner implements Runnable {
2327 PackageInfo mPackage;
2328 IBackupAgent mAgent;
2329 ParcelFileDescriptor mPipe;
2330 int mToken;
2331 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002332 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002333
2334 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002335 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002336 mPackage = pack;
2337 mAgent = agent;
2338 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2339 mToken = token;
2340 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002341 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002342 }
2343
2344 @Override
2345 public void run() {
2346 try {
2347 BackupDataOutput output = new BackupDataOutput(
2348 mPipe.getFileDescriptor());
2349
Christopher Tate73d73692012-01-20 17:11:31 -08002350 if (mWriteManifest) {
2351 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2352 writeAppManifest(mPackage, mManifestFile, mSendApk);
2353 FullBackup.backupToTar(mPackage.packageName, null, null,
2354 mFilesDir.getAbsolutePath(),
2355 mManifestFile.getAbsolutePath(),
2356 output);
2357 }
Christopher Tate7926a692011-07-11 11:31:57 -07002358
2359 if (mSendApk) {
2360 writeApkToBackup(mPackage, output);
2361 }
2362
Christopher Tatec58efa62011-08-01 19:20:14 -07002363 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002364 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002365 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2366 } catch (IOException e) {
2367 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2368 } catch (RemoteException e) {
2369 Slog.e(TAG, "Remote agent vanished during full backup of "
2370 + mPackage.packageName);
2371 } finally {
2372 try {
2373 mPipe.close();
2374 } catch (IOException e) {}
2375 }
2376 }
2377 }
2378
Christopher Tate4a627c72011-04-01 14:43:32 -07002379 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002380 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002381 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002382 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002383 mOutputFile = fd;
2384 mObserver = observer;
2385 mIncludeApks = includeApks;
2386 mIncludeShared = includeShared;
2387 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002388 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002389 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002390 mCurrentPassword = curPassword;
2391 // when backing up, if there is a current backup password, we require that
2392 // the user use a nonempty encryption password as well. if one is supplied
2393 // in the UI we use that, but if the UI was left empty we fall back to the
2394 // current backup password (which was supplied by the user as well).
2395 if (encryptPassword == null || "".equals(encryptPassword)) {
2396 mEncryptPassword = curPassword;
2397 } else {
2398 mEncryptPassword = encryptPassword;
2399 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002400 mLatchObject = latch;
2401
2402 mFilesDir = new File("/data/system");
2403 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2404 }
2405
2406 @Override
2407 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002408 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002409
Christopher Tateb0628bf2011-06-02 15:08:13 -07002410 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002411 sendStartBackup();
2412
2413 // doAllApps supersedes the package set if any
2414 if (mAllApps) {
2415 packagesToBackup = mPackageManager.getInstalledPackages(
2416 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002417 // Exclude system apps if we've been asked to do so
2418 if (mIncludeSystem == false) {
2419 for (int i = 0; i < packagesToBackup.size(); ) {
2420 PackageInfo pkg = packagesToBackup.get(i);
2421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2422 packagesToBackup.remove(i);
2423 } else {
2424 i++;
2425 }
2426 }
2427 }
2428 }
2429
2430 // Now process the command line argument packages, if any. Note that explicitly-
2431 // named system-partition packages will be included even if includeSystem was
2432 // set to false.
2433 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002434 for (String pkgName : mPackages) {
2435 try {
2436 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2437 PackageManager.GET_SIGNATURES));
2438 } catch (NameNotFoundException e) {
2439 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2440 }
2441 }
2442 }
2443
Christopher Tate73d73692012-01-20 17:11:31 -08002444 // Cull any packages that have indicated that backups are not permitted, as well
2445 // as any explicit mention of the 'special' shared-storage agent package (we
2446 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002447 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002448 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002449 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2450 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002451 packagesToBackup.remove(i);
2452 } else {
2453 i++;
2454 }
2455 }
2456
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002457 // Cull any packages that run as system-domain uids but do not define their
2458 // own backup agents
2459 for (int i = 0; i < packagesToBackup.size(); ) {
2460 PackageInfo pkg = packagesToBackup.get(i);
2461 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2462 && (pkg.applicationInfo.backupAgentName == null)) {
2463 if (MORE_DEBUG) {
2464 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2465 }
2466 packagesToBackup.remove(i);
2467 } else {
2468 i++;
2469 }
2470 }
2471
Christopher Tate7926a692011-07-11 11:31:57 -07002472 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002473 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002474
Christopher Tate4a627c72011-04-01 14:43:32 -07002475 PackageInfo pkg = null;
2476 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002477 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002478 boolean compressing = COMPRESS_FULL_BACKUPS;
2479 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002480
Christopher Tateeef4ae42011-08-05 13:15:53 -07002481 // Verify that the given password matches the currently-active
2482 // backup password, if any
2483 if (hasBackupPassword()) {
2484 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2485 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2486 return;
2487 }
2488 }
2489
Christopher Tate7bdb0962011-07-13 19:30:21 -07002490 // Write the global file header. All strings are UTF-8 encoded; lines end
2491 // with a '\n' byte. Actual backup data begins immediately following the
2492 // final '\n'.
2493 //
2494 // line 1: "ANDROID BACKUP"
2495 // line 2: backup file format version, currently "1"
2496 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002497 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2498 //
2499 // When line 4 is not "none", then additional header data follows:
2500 //
2501 // line 5: user password salt [hex]
2502 // line 6: master key checksum salt [hex]
2503 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2504 // line 8: IV of the user key [hex]
2505 // line 9: master key blob [hex]
2506 // IV of the master key, master key itself, master key checksum hash
2507 //
2508 // The master key checksum is the master key plus its checksum salt, run through
2509 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2510 // correct password for decrypting the archive: the master key decrypted from
2511 // the archive using the user-supplied password is also run through PBKDF2 in
2512 // this way, and if the result does not match the checksum as stored in the
2513 // archive, then we know that the user-supplied password does not match the
2514 // archive's.
2515 StringBuilder headerbuf = new StringBuilder(1024);
2516
Christopher Tate7bdb0962011-07-13 19:30:21 -07002517 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002518 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2519 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002520
2521 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002522 // Set up the encryption stage if appropriate, and emit the correct header
2523 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002524 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2525 } else {
2526 headerbuf.append("none\n");
2527 }
2528
Christopher Tate7bdb0962011-07-13 19:30:21 -07002529 byte[] header = headerbuf.toString().getBytes("UTF-8");
2530 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002531
2532 // Set up the compression stage feeding into the encryption stage (if any)
2533 if (compressing) {
2534 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2535 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2536 }
2537
2538 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002539 } catch (Exception e) {
2540 // Should never happen!
2541 Slog.e(TAG, "Unable to emit archive header", e);
2542 return;
2543 }
2544
Christopher Tate73d73692012-01-20 17:11:31 -08002545 // Shared storage if requested
2546 if (mIncludeShared) {
2547 try {
2548 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2549 packagesToBackup.add(pkg);
2550 } catch (NameNotFoundException e) {
2551 Slog.e(TAG, "Unable to find shared-storage backup handler");
2552 }
2553 }
2554
Christopher Tateb0628bf2011-06-02 15:08:13 -07002555 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002556 int N = packagesToBackup.size();
2557 for (int i = 0; i < N; i++) {
2558 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002559 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002560 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002561
Christopher Tate6853fcf2011-08-10 17:52:21 -07002562 // Done!
2563 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002564 } catch (RemoteException e) {
2565 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002566 } catch (Exception e) {
2567 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002568 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002569 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002570 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002571 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002572 mOutputFile.close();
2573 } catch (IOException e) {
2574 /* nothing we can do about this */
2575 }
2576 synchronized (mCurrentOpLock) {
2577 mCurrentOperations.clear();
2578 }
2579 synchronized (mLatchObject) {
2580 mLatchObject.set(true);
2581 mLatchObject.notifyAll();
2582 }
2583 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002584 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002585 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002586 }
2587 }
2588
Christopher Tate2efd2db2011-07-19 16:32:49 -07002589 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2590 OutputStream ofstream) throws Exception {
2591 // User key will be used to encrypt the master key.
2592 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002593 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002594 PBKDF2_HASH_ROUNDS);
2595
2596 // the master key is random for each backup
2597 byte[] masterPw = new byte[256 / 8];
2598 mRng.nextBytes(masterPw);
2599 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2600
2601 // primary encryption of the datastream with the random key
2602 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2603 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2604 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2605 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2606
2607 // line 4: name of encryption algorithm
2608 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2609 headerbuf.append('\n');
2610 // line 5: user password salt [hex]
2611 headerbuf.append(byteArrayToHex(newUserSalt));
2612 headerbuf.append('\n');
2613 // line 6: master key checksum salt [hex]
2614 headerbuf.append(byteArrayToHex(checksumSalt));
2615 headerbuf.append('\n');
2616 // line 7: number of PBKDF2 rounds used [decimal]
2617 headerbuf.append(PBKDF2_HASH_ROUNDS);
2618 headerbuf.append('\n');
2619
2620 // line 8: IV of the user key [hex]
2621 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2622 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2623
2624 byte[] IV = mkC.getIV();
2625 headerbuf.append(byteArrayToHex(IV));
2626 headerbuf.append('\n');
2627
2628 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2629 // [byte] IV length = Niv
2630 // [array of Niv bytes] IV itself
2631 // [byte] master key length = Nmk
2632 // [array of Nmk bytes] master key itself
2633 // [byte] MK checksum hash length = Nck
2634 // [array of Nck bytes] master key checksum hash
2635 //
2636 // The checksum is the (master key + checksum salt), run through the
2637 // stated number of PBKDF2 rounds
2638 IV = c.getIV();
2639 byte[] mk = masterKeySpec.getEncoded();
2640 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2641 checksumSalt, PBKDF2_HASH_ROUNDS);
2642
2643 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2644 + checksum.length + 3);
2645 DataOutputStream mkOut = new DataOutputStream(blob);
2646 mkOut.writeByte(IV.length);
2647 mkOut.write(IV);
2648 mkOut.writeByte(mk.length);
2649 mkOut.write(mk);
2650 mkOut.writeByte(checksum.length);
2651 mkOut.write(checksum);
2652 mkOut.flush();
2653 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2654 headerbuf.append(byteArrayToHex(encryptedMk));
2655 headerbuf.append('\n');
2656
2657 return finalOutput;
2658 }
2659
2660 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002661 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002662 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2663
2664 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2665 IApplicationThread.BACKUP_MODE_FULL);
2666 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002667 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002668 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002669 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002670
Christopher Tateb0628bf2011-06-02 15:08:13 -07002671 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002672 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002673 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002674 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002675 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2676 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2677 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2678
Christopher Tate73d73692012-01-20 17:11:31 -08002679 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002680
Christopher Tate7926a692011-07-11 11:31:57 -07002681 final int token = generateToken();
2682 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002683 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002684 pipes[1].close(); // the runner has dup'd it
2685 pipes[1] = null;
2686 Thread t = new Thread(runner);
2687 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002688
Christopher Tate7926a692011-07-11 11:31:57 -07002689 // Now pull data from the app and stuff it into the compressor
2690 try {
2691 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2692 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002693
Christopher Tate7926a692011-07-11 11:31:57 -07002694 byte[] buffer = new byte[16 * 1024];
2695 int chunkTotal;
2696 while ((chunkTotal = in.readInt()) > 0) {
2697 while (chunkTotal > 0) {
2698 int toRead = (chunkTotal > buffer.length)
2699 ? buffer.length : chunkTotal;
2700 int nRead = in.read(buffer, 0, toRead);
2701 out.write(buffer, 0, nRead);
2702 chunkTotal -= nRead;
2703 }
2704 }
2705 } catch (IOException e) {
2706 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002707 }
2708
Christopher Tateb0628bf2011-06-02 15:08:13 -07002709 if (!waitUntilOperationComplete(token)) {
2710 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2711 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002712 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002713 }
Christopher Tate7926a692011-07-11 11:31:57 -07002714
Christopher Tateb0628bf2011-06-02 15:08:13 -07002715 } catch (IOException e) {
2716 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002717 } finally {
2718 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002719 // flush after every package
2720 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002721 if (pipes != null) {
2722 if (pipes[0] != null) pipes[0].close();
2723 if (pipes[1] != null) pipes[1].close();
2724 }
Christopher Tate7926a692011-07-11 11:31:57 -07002725 } catch (IOException e) {
2726 Slog.w(TAG, "Error bringing down backup stack");
2727 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002728 }
2729 } else {
2730 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2731 }
2732 tearDown(pkg);
2733 }
2734
Christopher Tate79ec80d2011-06-24 14:58:49 -07002735 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2736 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2737 final String appSourceDir = pkg.applicationInfo.sourceDir;
2738 final String apkDir = new File(appSourceDir).getParent();
2739 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2740 apkDir, appSourceDir, output);
2741
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002742 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2743 // doesn't have access to external storage.
2744
Christopher Tate79ec80d2011-06-24 14:58:49 -07002745 // Save associated .obb content if it exists and we did save the apk
2746 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002747 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2748 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002749 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002750 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002751 File[] obbFiles = obbDir.listFiles();
2752 if (obbFiles != null) {
2753 final String obbDirName = obbDir.getAbsolutePath();
2754 for (File obb : obbFiles) {
2755 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2756 obbDirName, obb.getAbsolutePath(), output);
2757 }
2758 }
2759 }
2760 }
2761
Christopher Tate6853fcf2011-08-10 17:52:21 -07002762 private void finalizeBackup(OutputStream out) {
2763 try {
2764 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2765 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2766 out.write(eof);
2767 } catch (IOException e) {
2768 Slog.w(TAG, "Error attempting to finalize backup stream");
2769 }
2770 }
2771
Christopher Tate4a627c72011-04-01 14:43:32 -07002772 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2773 throws IOException {
2774 // Manifest format. All data are strings ending in LF:
2775 // BACKUP_MANIFEST_VERSION, currently 1
2776 //
2777 // Version 1:
2778 // package name
2779 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002780 // platform versionCode
2781 // getInstallerPackageName() for this package (maybe empty)
2782 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002783 // number of signatures == N
2784 // N*: signature byte array in ascii format per Signature.toCharsString()
2785 StringBuilder builder = new StringBuilder(4096);
2786 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2787
2788 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2789 printer.println(pkg.packageName);
2790 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002791 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2792
2793 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2794 printer.println((installerName != null) ? installerName : "");
2795
Christopher Tate4a627c72011-04-01 14:43:32 -07002796 printer.println(withApk ? "1" : "0");
2797 if (pkg.signatures == null) {
2798 printer.println("0");
2799 } else {
2800 printer.println(Integer.toString(pkg.signatures.length));
2801 for (Signature sig : pkg.signatures) {
2802 printer.println(sig.toCharsString());
2803 }
2804 }
2805
2806 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002807 outstream.write(builder.toString().getBytes());
2808 outstream.close();
2809 }
2810
2811 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002812 if (pkg != null) {
2813 final ApplicationInfo app = pkg.applicationInfo;
2814 if (app != null) {
2815 try {
2816 // unbind and tidy up even on timeout or failure, just in case
2817 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002818
Christopher Tateb0628bf2011-06-02 15:08:13 -07002819 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002820 if (app.uid != Process.SYSTEM_UID
2821 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002822 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002823 mActivityManager.killApplicationProcess(app.processName, app.uid);
2824 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002825 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002826 }
2827 } catch (RemoteException e) {
2828 Slog.d(TAG, "Lost app trying to shut down");
2829 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002830 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002831 }
2832 }
2833
2834 // wrappers for observer use
2835 void sendStartBackup() {
2836 if (mObserver != null) {
2837 try {
2838 mObserver.onStartBackup();
2839 } catch (RemoteException e) {
2840 Slog.w(TAG, "full backup observer went away: startBackup");
2841 mObserver = null;
2842 }
2843 }
2844 }
2845
2846 void sendOnBackupPackage(String name) {
2847 if (mObserver != null) {
2848 try {
2849 // TODO: use a more user-friendly name string
2850 mObserver.onBackupPackage(name);
2851 } catch (RemoteException e) {
2852 Slog.w(TAG, "full backup observer went away: backupPackage");
2853 mObserver = null;
2854 }
2855 }
2856 }
2857
2858 void sendEndBackup() {
2859 if (mObserver != null) {
2860 try {
2861 mObserver.onEndBackup();
2862 } catch (RemoteException e) {
2863 Slog.w(TAG, "full backup observer went away: endBackup");
2864 mObserver = null;
2865 }
2866 }
2867 }
2868 }
2869
2870
Christopher Tate75a99702011-05-18 16:28:19 -07002871 // ----- Full restore from a file/socket -----
2872
2873 // Description of a file in the restore datastream
2874 static class FileMetadata {
2875 String packageName; // name of the owning app
2876 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002877 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002878 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2879 String path; // subpath within the semantic domain
2880 long mode; // e.g. 0666 (actually int)
2881 long mtime; // last mod time, UTC time_t (actually int)
2882 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002883
2884 @Override
2885 public String toString() {
2886 StringBuilder sb = new StringBuilder(128);
2887 sb.append("FileMetadata{");
2888 sb.append(packageName); sb.append(',');
2889 sb.append(type); sb.append(',');
2890 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2891 sb.append(size);
2892 sb.append('}');
2893 return sb.toString();
2894 }
Christopher Tate75a99702011-05-18 16:28:19 -07002895 }
2896
2897 enum RestorePolicy {
2898 IGNORE,
2899 ACCEPT,
2900 ACCEPT_IF_APK
2901 }
2902
2903 class PerformFullRestoreTask implements Runnable {
2904 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002905 String mCurrentPassword;
2906 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002907 IFullBackupRestoreObserver mObserver;
2908 AtomicBoolean mLatchObject;
2909 IBackupAgent mAgent;
2910 String mAgentPackage;
2911 ApplicationInfo mTargetApp;
2912 ParcelFileDescriptor[] mPipes = null;
2913
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002914 long mBytes;
2915
Christopher Tate75a99702011-05-18 16:28:19 -07002916 // possible handling states for a given package in the restore dataset
2917 final HashMap<String, RestorePolicy> mPackagePolicies
2918 = new HashMap<String, RestorePolicy>();
2919
2920 // installer package names for each encountered app, derived from the manifests
2921 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2922
2923 // Signatures for a given package found in its manifest file
2924 final HashMap<String, Signature[]> mManifestSignatures
2925 = new HashMap<String, Signature[]>();
2926
2927 // Packages we've already wiped data on when restoring their first file
2928 final HashSet<String> mClearedPackages = new HashSet<String>();
2929
Christopher Tate728a1c42011-07-28 18:03:03 -07002930 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002931 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002932 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002933 mCurrentPassword = curPassword;
2934 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002935 mObserver = observer;
2936 mLatchObject = latch;
2937 mAgent = null;
2938 mAgentPackage = null;
2939 mTargetApp = null;
2940
2941 // Which packages we've already wiped data on. We prepopulate this
2942 // with a whitelist of packages known to be unclearable.
2943 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002944 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002945
Christopher Tate75a99702011-05-18 16:28:19 -07002946 }
2947
2948 class RestoreFileRunnable implements Runnable {
2949 IBackupAgent mAgent;
2950 FileMetadata mInfo;
2951 ParcelFileDescriptor mSocket;
2952 int mToken;
2953
2954 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2955 ParcelFileDescriptor socket, int token) throws IOException {
2956 mAgent = agent;
2957 mInfo = info;
2958 mToken = token;
2959
2960 // This class is used strictly for process-local binder invocations. The
2961 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2962 // do not automatically get a 'dup'ed descriptor that we can can continue
2963 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2964 // before proceeding to do the restore.
2965 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2966 }
2967
2968 @Override
2969 public void run() {
2970 try {
2971 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2972 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2973 mToken, mBackupManagerBinder);
2974 } catch (RemoteException e) {
2975 // never happens; this is used strictly for local binder calls
2976 }
2977 }
2978 }
2979
2980 @Override
2981 public void run() {
2982 Slog.i(TAG, "--- Performing full-dataset restore ---");
2983 sendStartRestore();
2984
Christopher Tateb0628bf2011-06-02 15:08:13 -07002985 // Are we able to restore shared-storage data?
2986 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002987 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002988 }
2989
Christopher Tate2efd2db2011-07-19 16:32:49 -07002990 FileInputStream rawInStream = null;
2991 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002992 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002993 if (hasBackupPassword()) {
2994 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2995 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2996 return;
2997 }
2998 }
2999
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003000 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003001 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003002 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3003 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003004
3005 // First, parse out the unencrypted/uncompressed header
3006 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003007 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003008 final InputStream in;
3009
3010 boolean okay = false;
3011 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3012 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003013 rawDataIn.readFully(streamHeader);
3014 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3015 if (Arrays.equals(magicBytes, streamHeader)) {
3016 // okay, header looks good. now parse out the rest of the fields.
3017 String s = readHeaderLine(rawInStream);
3018 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3019 // okay, it's a version we recognize
3020 s = readHeaderLine(rawInStream);
3021 compressed = (Integer.parseInt(s) != 0);
3022 s = readHeaderLine(rawInStream);
3023 if (s.equals("none")) {
3024 // no more header to parse; we're good to go
3025 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003026 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003027 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3028 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003029 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003030 }
3031 } else Slog.w(TAG, "Archive is encrypted but no password given");
3032 } else Slog.w(TAG, "Wrong header version: " + s);
3033 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003034
3035 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003036 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003037 return;
3038 }
3039
3040 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003041 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003042
3043 boolean didRestore;
3044 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003045 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003046 } while (didRestore);
3047
Christopher Tatec58efa62011-08-01 19:20:14 -07003048 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003049 } catch (IOException e) {
3050 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003051 } finally {
3052 tearDownPipes();
3053 tearDownAgent(mTargetApp);
3054
3055 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003056 if (rawDataIn != null) rawDataIn.close();
3057 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003058 mInputFile.close();
3059 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003060 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003061 /* nothing we can do about this */
3062 }
3063 synchronized (mCurrentOpLock) {
3064 mCurrentOperations.clear();
3065 }
3066 synchronized (mLatchObject) {
3067 mLatchObject.set(true);
3068 mLatchObject.notifyAll();
3069 }
3070 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003071 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003072 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003073 }
3074 }
3075
Christopher Tate7bdb0962011-07-13 19:30:21 -07003076 String readHeaderLine(InputStream in) throws IOException {
3077 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003078 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003079 while ((c = in.read()) >= 0) {
3080 if (c == '\n') break; // consume and discard the newlines
3081 buffer.append((char)c);
3082 }
3083 return buffer.toString();
3084 }
3085
Christopher Tate2efd2db2011-07-19 16:32:49 -07003086 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3087 InputStream result = null;
3088 try {
3089 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3090
3091 String userSaltHex = readHeaderLine(rawInStream); // 5
3092 byte[] userSalt = hexToByteArray(userSaltHex);
3093
3094 String ckSaltHex = readHeaderLine(rawInStream); // 6
3095 byte[] ckSalt = hexToByteArray(ckSaltHex);
3096
3097 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3098 String userIvHex = readHeaderLine(rawInStream); // 8
3099
3100 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3101
3102 // decrypt the master key blob
3103 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003104 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003105 rounds);
3106 byte[] IV = hexToByteArray(userIvHex);
3107 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3108 c.init(Cipher.DECRYPT_MODE,
3109 new SecretKeySpec(userKey.getEncoded(), "AES"),
3110 ivSpec);
3111 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3112 byte[] mkBlob = c.doFinal(mkCipher);
3113
3114 // first, the master key IV
3115 int offset = 0;
3116 int len = mkBlob[offset++];
3117 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3118 offset += len;
3119 // then the master key itself
3120 len = mkBlob[offset++];
3121 byte[] mk = Arrays.copyOfRange(mkBlob,
3122 offset, offset + len);
3123 offset += len;
3124 // and finally the master key checksum hash
3125 len = mkBlob[offset++];
3126 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3127 offset, offset + len);
3128
3129 // now validate the decrypted master key against the checksum
3130 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3131 if (Arrays.equals(calculatedCk, mkChecksum)) {
3132 ivSpec = new IvParameterSpec(IV);
3133 c.init(Cipher.DECRYPT_MODE,
3134 new SecretKeySpec(mk, "AES"),
3135 ivSpec);
3136 // Only if all of the above worked properly will 'result' be assigned
3137 result = new CipherInputStream(rawInStream, c);
3138 } else Slog.w(TAG, "Incorrect password");
3139 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3140 } catch (InvalidAlgorithmParameterException e) {
3141 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3142 } catch (BadPaddingException e) {
3143 // This case frequently occurs when the wrong password is used to decrypt
3144 // the master key. Use the identical "incorrect password" log text as is
3145 // used in the checksum failure log in order to avoid providing additional
3146 // information to an attacker.
3147 Slog.w(TAG, "Incorrect password");
3148 } catch (IllegalBlockSizeException e) {
3149 Slog.w(TAG, "Invalid block size in master key");
3150 } catch (NoSuchAlgorithmException e) {
3151 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3152 } catch (NoSuchPaddingException e) {
3153 Slog.e(TAG, "Needed padding mechanism unavailable!");
3154 } catch (InvalidKeyException e) {
3155 Slog.w(TAG, "Illegal password; aborting");
3156 } catch (NumberFormatException e) {
3157 Slog.w(TAG, "Can't parse restore data header");
3158 } catch (IOException e) {
3159 Slog.w(TAG, "Can't read input header");
3160 }
3161
3162 return result;
3163 }
3164
Christopher Tate75a99702011-05-18 16:28:19 -07003165 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3166 FileMetadata info;
3167 try {
3168 info = readTarHeaders(instream);
3169 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003170 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003171 dumpFileMetadata(info);
3172 }
3173
3174 final String pkg = info.packageName;
3175 if (!pkg.equals(mAgentPackage)) {
3176 // okay, change in package; set up our various
3177 // bookkeeping if we haven't seen it yet
3178 if (!mPackagePolicies.containsKey(pkg)) {
3179 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3180 }
3181
3182 // Clean up the previous agent relationship if necessary,
3183 // and let the observer know we're considering a new app.
3184 if (mAgent != null) {
3185 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3186 tearDownPipes();
3187 tearDownAgent(mTargetApp);
3188 mTargetApp = null;
3189 mAgentPackage = null;
3190 }
3191 }
3192
3193 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3194 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3195 mPackageInstallers.put(pkg, info.installerPackageName);
3196 // We've read only the manifest content itself at this point,
3197 // so consume the footer before looping around to the next
3198 // input file
3199 skipTarPadding(info.size, instream);
3200 sendOnRestorePackage(pkg);
3201 } else {
3202 // Non-manifest, so it's actual file data. Is this a package
3203 // we're ignoring?
3204 boolean okay = true;
3205 RestorePolicy policy = mPackagePolicies.get(pkg);
3206 switch (policy) {
3207 case IGNORE:
3208 okay = false;
3209 break;
3210
3211 case ACCEPT_IF_APK:
3212 // If we're in accept-if-apk state, then the first file we
3213 // see MUST be the apk.
3214 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3215 if (DEBUG) Slog.d(TAG, "APK file; installing");
3216 // Try to install the app.
3217 String installerName = mPackageInstallers.get(pkg);
3218 okay = installApk(info, installerName, instream);
3219 // good to go; promote to ACCEPT
3220 mPackagePolicies.put(pkg, (okay)
3221 ? RestorePolicy.ACCEPT
3222 : RestorePolicy.IGNORE);
3223 // At this point we've consumed this file entry
3224 // ourselves, so just strip the tar footer and
3225 // go on to the next file in the input stream
3226 skipTarPadding(info.size, instream);
3227 return true;
3228 } else {
3229 // File data before (or without) the apk. We can't
3230 // handle it coherently in this case so ignore it.
3231 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3232 okay = false;
3233 }
3234 break;
3235
3236 case ACCEPT:
3237 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3238 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3239 // we can take the data without the apk, so we
3240 // *want* to do so. skip the apk by declaring this
3241 // one file not-okay without changing the restore
3242 // policy for the package.
3243 okay = false;
3244 }
3245 break;
3246
3247 default:
3248 // Something has gone dreadfully wrong when determining
3249 // the restore policy from the manifest. Ignore the
3250 // rest of this package's data.
3251 Slog.e(TAG, "Invalid policy from manifest");
3252 okay = false;
3253 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3254 break;
3255 }
3256
3257 // If the policy is satisfied, go ahead and set up to pipe the
3258 // data to the agent.
3259 if (DEBUG && okay && mAgent != null) {
3260 Slog.i(TAG, "Reusing existing agent instance");
3261 }
3262 if (okay && mAgent == null) {
3263 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3264
3265 try {
3266 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3267
3268 // If we haven't sent any data to this app yet, we probably
3269 // need to clear it first. Check that.
3270 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003271 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003272 // responsible for coherently managing a full
3273 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003274 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003275 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3276 clearApplicationDataSynchronous(pkg);
3277 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003278 if (DEBUG) Slog.d(TAG, "backup agent ("
3279 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003280 }
3281 mClearedPackages.add(pkg);
3282 } else {
3283 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3284 }
3285
3286 // All set; now set up the IPC and launch the agent
3287 setUpPipes();
3288 mAgent = bindToAgentSynchronous(mTargetApp,
3289 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3290 mAgentPackage = pkg;
3291 } catch (IOException e) {
3292 // fall through to error handling
3293 } catch (NameNotFoundException e) {
3294 // fall through to error handling
3295 }
3296
3297 if (mAgent == null) {
3298 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3299 okay = false;
3300 tearDownPipes();
3301 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3302 }
3303 }
3304
3305 // Sanity check: make sure we never give data to the wrong app. This
3306 // should never happen but a little paranoia here won't go amiss.
3307 if (okay && !pkg.equals(mAgentPackage)) {
3308 Slog.e(TAG, "Restoring data for " + pkg
3309 + " but agent is for " + mAgentPackage);
3310 okay = false;
3311 }
3312
3313 // At this point we have an agent ready to handle the full
3314 // restore data as well as a pipe for sending data to
3315 // that agent. Tell the agent to start reading from the
3316 // pipe.
3317 if (okay) {
3318 boolean agentSuccess = true;
3319 long toCopy = info.size;
3320 final int token = generateToken();
3321 try {
3322 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3323 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003324 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003325 // fire up the app's agent listening on the socket. If
3326 // the agent is running in the system process we can't
3327 // just invoke it asynchronously, so we provide a thread
3328 // for it here.
3329 if (mTargetApp.processName.equals("system")) {
3330 Slog.d(TAG, "system process agent - spinning a thread");
3331 RestoreFileRunnable runner = new RestoreFileRunnable(
3332 mAgent, info, mPipes[0], token);
3333 new Thread(runner).start();
3334 } else {
3335 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3336 info.domain, info.path, info.mode, info.mtime,
3337 token, mBackupManagerBinder);
3338 }
3339 } catch (IOException e) {
3340 // couldn't dup the socket for a process-local restore
3341 Slog.d(TAG, "Couldn't establish restore");
3342 agentSuccess = false;
3343 okay = false;
3344 } catch (RemoteException e) {
3345 // whoops, remote agent went away. We'll eat the content
3346 // ourselves, then, and not copy it over.
3347 Slog.e(TAG, "Agent crashed during full restore");
3348 agentSuccess = false;
3349 okay = false;
3350 }
3351
3352 // Copy over the data if the agent is still good
3353 if (okay) {
3354 boolean pipeOkay = true;
3355 FileOutputStream pipe = new FileOutputStream(
3356 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003357 while (toCopy > 0) {
3358 int toRead = (toCopy > buffer.length)
3359 ? buffer.length : (int)toCopy;
3360 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003361 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003362 if (nRead <= 0) break;
3363 toCopy -= nRead;
3364
3365 // send it to the output pipe as long as things
3366 // are still good
3367 if (pipeOkay) {
3368 try {
3369 pipe.write(buffer, 0, nRead);
3370 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003371 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003372 pipeOkay = false;
3373 }
3374 }
3375 }
3376
3377 // done sending that file! Now we just need to consume
3378 // the delta from info.size to the end of block.
3379 skipTarPadding(info.size, instream);
3380
3381 // and now that we've sent it all, wait for the remote
3382 // side to acknowledge receipt
3383 agentSuccess = waitUntilOperationComplete(token);
3384 }
3385
3386 // okay, if the remote end failed at any point, deal with
3387 // it by ignoring the rest of the restore on it
3388 if (!agentSuccess) {
3389 mBackupHandler.removeMessages(MSG_TIMEOUT);
3390 tearDownPipes();
3391 tearDownAgent(mTargetApp);
3392 mAgent = null;
3393 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3394 }
3395 }
3396
3397 // Problems setting up the agent communication, or an already-
3398 // ignored package: skip to the next tar stream entry by
3399 // reading and discarding this file.
3400 if (!okay) {
3401 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3402 long bytesToConsume = (info.size + 511) & ~511;
3403 while (bytesToConsume > 0) {
3404 int toRead = (bytesToConsume > buffer.length)
3405 ? buffer.length : (int)bytesToConsume;
3406 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003407 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003408 if (nRead <= 0) break;
3409 bytesToConsume -= nRead;
3410 }
3411 }
3412 }
3413 }
3414 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003415 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003416 // treat as EOF
3417 info = null;
3418 }
3419
3420 return (info != null);
3421 }
3422
3423 void setUpPipes() throws IOException {
3424 mPipes = ParcelFileDescriptor.createPipe();
3425 }
3426
3427 void tearDownPipes() {
3428 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003429 try {
3430 mPipes[0].close();
3431 mPipes[0] = null;
3432 mPipes[1].close();
3433 mPipes[1] = null;
3434 } catch (IOException e) {
3435 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003436 }
3437 mPipes = null;
3438 }
3439 }
3440
3441 void tearDownAgent(ApplicationInfo app) {
3442 if (mAgent != null) {
3443 try {
3444 // unbind and tidy up even on timeout or failure, just in case
3445 mActivityManager.unbindBackupAgent(app);
3446
3447 // The agent was running with a stub Application object, so shut it down.
3448 // !!! We hardcode the confirmation UI's package name here rather than use a
3449 // manifest flag! TODO something less direct.
3450 if (app.uid != Process.SYSTEM_UID
3451 && !app.packageName.equals("com.android.backupconfirm")) {
3452 if (DEBUG) Slog.d(TAG, "Killing host process");
3453 mActivityManager.killApplicationProcess(app.processName, app.uid);
3454 } else {
3455 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3456 }
3457 } catch (RemoteException e) {
3458 Slog.d(TAG, "Lost app trying to shut down");
3459 }
3460 mAgent = null;
3461 }
3462 }
3463
3464 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3465 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003466 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003467 int mResult;
3468
3469 public void reset() {
3470 synchronized (mDone) {
3471 mDone.set(false);
3472 }
3473 }
3474
3475 public void waitForCompletion() {
3476 synchronized (mDone) {
3477 while (mDone.get() == false) {
3478 try {
3479 mDone.wait();
3480 } catch (InterruptedException e) { }
3481 }
3482 }
3483 }
3484
3485 int getResult() {
3486 return mResult;
3487 }
3488
3489 @Override
3490 public void packageInstalled(String packageName, int returnCode)
3491 throws RemoteException {
3492 synchronized (mDone) {
3493 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003494 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003495 mDone.set(true);
3496 mDone.notifyAll();
3497 }
3498 }
3499 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003500
3501 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3502 final AtomicBoolean mDone = new AtomicBoolean();
3503 int mResult;
3504
3505 public void reset() {
3506 synchronized (mDone) {
3507 mDone.set(false);
3508 }
3509 }
3510
3511 public void waitForCompletion() {
3512 synchronized (mDone) {
3513 while (mDone.get() == false) {
3514 try {
3515 mDone.wait();
3516 } catch (InterruptedException e) { }
3517 }
3518 }
3519 }
3520
3521 @Override
3522 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3523 synchronized (mDone) {
3524 mResult = returnCode;
3525 mDone.set(true);
3526 mDone.notifyAll();
3527 }
3528 }
3529 }
3530
Christopher Tate75a99702011-05-18 16:28:19 -07003531 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003532 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003533
3534 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3535 boolean okay = true;
3536
3537 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3538
3539 // The file content is an .apk file. Copy it out to a staging location and
3540 // attempt to install it.
3541 File apkFile = new File(mDataDir, info.packageName);
3542 try {
3543 FileOutputStream apkStream = new FileOutputStream(apkFile);
3544 byte[] buffer = new byte[32 * 1024];
3545 long size = info.size;
3546 while (size > 0) {
3547 long toRead = (buffer.length < size) ? buffer.length : size;
3548 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003549 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003550 apkStream.write(buffer, 0, didRead);
3551 size -= didRead;
3552 }
3553 apkStream.close();
3554
3555 // make sure the installer can read it
3556 apkFile.setReadable(true, false);
3557
3558 // Now install it
3559 Uri packageUri = Uri.fromFile(apkFile);
3560 mInstallObserver.reset();
3561 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003562 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3563 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003564 mInstallObserver.waitForCompletion();
3565
3566 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3567 // The only time we continue to accept install of data even if the
3568 // apk install failed is if we had already determined that we could
3569 // accept the data regardless.
3570 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3571 okay = false;
3572 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003573 } else {
3574 // Okay, the install succeeded. Make sure it was the right app.
3575 boolean uninstall = false;
3576 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3577 Slog.w(TAG, "Restore stream claimed to include apk for "
3578 + info.packageName + " but apk was really "
3579 + mInstallObserver.mPackageName);
3580 // delete the package we just put in place; it might be fraudulent
3581 okay = false;
3582 uninstall = true;
3583 } else {
3584 try {
3585 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3586 PackageManager.GET_SIGNATURES);
3587 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3588 Slog.w(TAG, "Restore stream contains apk of package "
3589 + info.packageName + " but it disallows backup/restore");
3590 okay = false;
3591 } else {
3592 // So far so good -- do the signatures match the manifest?
3593 Signature[] sigs = mManifestSignatures.get(info.packageName);
3594 if (!signaturesMatch(sigs, pkg)) {
3595 Slog.w(TAG, "Installed app " + info.packageName
3596 + " signatures do not match restore manifest");
3597 okay = false;
3598 uninstall = true;
3599 }
3600 }
3601 } catch (NameNotFoundException e) {
3602 Slog.w(TAG, "Install of package " + info.packageName
3603 + " succeeded but now not found");
3604 okay = false;
3605 }
3606 }
3607
3608 // If we're not okay at this point, we need to delete the package
3609 // that we just installed.
3610 if (uninstall) {
3611 mDeleteObserver.reset();
3612 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3613 mDeleteObserver, 0);
3614 mDeleteObserver.waitForCompletion();
3615 }
Christopher Tate75a99702011-05-18 16:28:19 -07003616 }
3617 } catch (IOException e) {
3618 Slog.e(TAG, "Unable to transcribe restored apk for install");
3619 okay = false;
3620 } finally {
3621 apkFile.delete();
3622 }
3623
3624 return okay;
3625 }
3626
3627 // Given an actual file content size, consume the post-content padding mandated
3628 // by the tar format.
3629 void skipTarPadding(long size, InputStream instream) throws IOException {
3630 long partial = (size + 512) % 512;
3631 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003632 final int needed = 512 - (int)partial;
3633 byte[] buffer = new byte[needed];
3634 if (readExactly(instream, buffer, 0, needed) == needed) {
3635 mBytes += needed;
3636 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003637 }
3638 }
3639
3640 // Returns a policy constant; takes a buffer arg to reduce memory churn
3641 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3642 throws IOException {
3643 // Fail on suspiciously large manifest files
3644 if (info.size > 64 * 1024) {
3645 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3646 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003647
Christopher Tate75a99702011-05-18 16:28:19 -07003648 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003649 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3650 mBytes += info.size;
3651 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003652
3653 RestorePolicy policy = RestorePolicy.IGNORE;
3654 String[] str = new String[1];
3655 int offset = 0;
3656
3657 try {
3658 offset = extractLine(buffer, offset, str);
3659 int version = Integer.parseInt(str[0]);
3660 if (version == BACKUP_MANIFEST_VERSION) {
3661 offset = extractLine(buffer, offset, str);
3662 String manifestPackage = str[0];
3663 // TODO: handle <original-package>
3664 if (manifestPackage.equals(info.packageName)) {
3665 offset = extractLine(buffer, offset, str);
3666 version = Integer.parseInt(str[0]); // app version
3667 offset = extractLine(buffer, offset, str);
3668 int platformVersion = Integer.parseInt(str[0]);
3669 offset = extractLine(buffer, offset, str);
3670 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3671 offset = extractLine(buffer, offset, str);
3672 boolean hasApk = str[0].equals("1");
3673 offset = extractLine(buffer, offset, str);
3674 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003675 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003676 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003677 for (int i = 0; i < numSigs; i++) {
3678 offset = extractLine(buffer, offset, str);
3679 sigs[i] = new Signature(str[0]);
3680 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003681 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003682
3683 // Okay, got the manifest info we need...
3684 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003685 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3686 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003687 // Fall through to IGNORE if the app explicitly disallows backup
3688 final int flags = pkgInfo.applicationInfo.flags;
3689 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003690 // Restore system-uid-space packages only if they have
3691 // defined a custom backup agent
3692 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3693 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3694 // Verify signatures against any installed version; if they
3695 // don't match, then we fall though and ignore the data. The
3696 // signatureMatch() method explicitly ignores the signature
3697 // check for packages installed on the system partition, because
3698 // such packages are signed with the platform cert instead of
3699 // the app developer's cert, so they're different on every
3700 // device.
3701 if (signaturesMatch(sigs, pkgInfo)) {
3702 if (pkgInfo.versionCode >= version) {
3703 Slog.i(TAG, "Sig + version match; taking data");
3704 policy = RestorePolicy.ACCEPT;
3705 } else {
3706 // The data is from a newer version of the app than
3707 // is presently installed. That means we can only
3708 // use it if the matching apk is also supplied.
3709 Slog.d(TAG, "Data version " + version
3710 + " is newer than installed version "
3711 + pkgInfo.versionCode + " - requiring apk");
3712 policy = RestorePolicy.ACCEPT_IF_APK;
3713 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003714 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003715 Slog.w(TAG, "Restore manifest signatures do not match "
3716 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003717 }
Christopher Tate75a99702011-05-18 16:28:19 -07003718 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003719 Slog.w(TAG, "Package " + info.packageName
3720 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003721 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003722 } else {
3723 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3724 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003725 }
3726 } catch (NameNotFoundException e) {
3727 // Okay, the target app isn't installed. We can process
3728 // the restore properly only if the dataset provides the
3729 // apk file and we can successfully install it.
3730 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3731 + " not installed; requiring apk in dataset");
3732 policy = RestorePolicy.ACCEPT_IF_APK;
3733 }
3734
3735 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3736 Slog.i(TAG, "Cannot restore package " + info.packageName
3737 + " without the matching .apk");
3738 }
3739 } else {
3740 Slog.i(TAG, "Missing signature on backed-up package "
3741 + info.packageName);
3742 }
3743 } else {
3744 Slog.i(TAG, "Expected package " + info.packageName
3745 + " but restore manifest claims " + manifestPackage);
3746 }
3747 } else {
3748 Slog.i(TAG, "Unknown restore manifest version " + version
3749 + " for package " + info.packageName);
3750 }
3751 } catch (NumberFormatException e) {
3752 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003753 } catch (IllegalArgumentException e) {
3754 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003755 }
3756
3757 return policy;
3758 }
3759
3760 // Builds a line from a byte buffer starting at 'offset', and returns
3761 // the index of the next unconsumed data in the buffer.
3762 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3763 final int end = buffer.length;
3764 if (offset >= end) throw new IOException("Incomplete data");
3765
3766 int pos;
3767 for (pos = offset; pos < end; pos++) {
3768 byte c = buffer[pos];
3769 // at LF we declare end of line, and return the next char as the
3770 // starting point for the next time through
3771 if (c == '\n') {
3772 break;
3773 }
3774 }
3775 outStr[0] = new String(buffer, offset, pos - offset);
3776 pos++; // may be pointing an extra byte past the end but that's okay
3777 return pos;
3778 }
3779
3780 void dumpFileMetadata(FileMetadata info) {
3781 if (DEBUG) {
3782 StringBuilder b = new StringBuilder(128);
3783
3784 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003785 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003786 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3787 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3788 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3789 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3790 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3791 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3792 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3793 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3794 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3795 b.append(String.format(" %9d ", info.size));
3796
3797 Date stamp = new Date(info.mtime);
3798 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3799
3800 b.append(info.packageName);
3801 b.append(" :: ");
3802 b.append(info.domain);
3803 b.append(" :: ");
3804 b.append(info.path);
3805
3806 Slog.i(TAG, b.toString());
3807 }
3808 }
3809 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3810 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3811 byte[] block = new byte[512];
3812 FileMetadata info = null;
3813
3814 boolean gotHeader = readTarHeader(instream, block);
3815 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003816 try {
3817 // okay, presume we're okay, and extract the various metadata
3818 info = new FileMetadata();
3819 info.size = extractRadix(block, 124, 12, 8);
3820 info.mtime = extractRadix(block, 136, 12, 8);
3821 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003822
Christopher Tate2efd2db2011-07-19 16:32:49 -07003823 info.path = extractString(block, 345, 155); // prefix
3824 String path = extractString(block, 0, 100);
3825 if (path.length() > 0) {
3826 if (info.path.length() > 0) info.path += '/';
3827 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003828 }
Christopher Tate75a99702011-05-18 16:28:19 -07003829
Christopher Tate2efd2db2011-07-19 16:32:49 -07003830 // tar link indicator field: 1 byte at offset 156 in the header.
3831 int typeChar = block[156];
3832 if (typeChar == 'x') {
3833 // pax extended header, so we need to read that
3834 gotHeader = readPaxExtendedHeader(instream, info);
3835 if (gotHeader) {
3836 // and after a pax extended header comes another real header -- read
3837 // that to find the real file type
3838 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003839 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003840 if (!gotHeader) throw new IOException("Bad or missing pax header");
3841
3842 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003843 }
Christopher Tate75a99702011-05-18 16:28:19 -07003844
Christopher Tate2efd2db2011-07-19 16:32:49 -07003845 switch (typeChar) {
3846 case '0': info.type = BackupAgent.TYPE_FILE; break;
3847 case '5': {
3848 info.type = BackupAgent.TYPE_DIRECTORY;
3849 if (info.size != 0) {
3850 Slog.w(TAG, "Directory entry with nonzero size in header");
3851 info.size = 0;
3852 }
3853 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003854 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003855 case 0: {
3856 // presume EOF
3857 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3858 return null;
3859 }
3860 default: {
3861 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3862 throw new IOException("Unknown entity type " + typeChar);
3863 }
Christopher Tate75a99702011-05-18 16:28:19 -07003864 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003865
3866 // Parse out the path
3867 //
3868 // first: apps/shared/unrecognized
3869 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3870 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3871 // File in shared storage. !!! TODO: implement this.
3872 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003873 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003874 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3875 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3876 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3877 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3878 // App content! Parse out the package name and domain
3879
3880 // strip the apps/ prefix
3881 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3882
3883 // extract the package name
3884 int slash = info.path.indexOf('/');
3885 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3886 info.packageName = info.path.substring(0, slash);
3887 info.path = info.path.substring(slash+1);
3888
3889 // if it's a manifest we're done, otherwise parse out the domains
3890 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3891 slash = info.path.indexOf('/');
3892 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3893 info.domain = info.path.substring(0, slash);
3894 // validate that it's one of the domains we understand
3895 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3896 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3897 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3898 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3899 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3900 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3901 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3902 throw new IOException("Unrecognized domain " + info.domain);
3903 }
3904
3905 info.path = info.path.substring(slash + 1);
3906 }
3907 }
3908 } catch (IOException e) {
3909 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003910 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003911 HEXLOG(block);
3912 }
3913 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003914 }
3915 }
3916 return info;
3917 }
3918
Christopher Tate2efd2db2011-07-19 16:32:49 -07003919 private void HEXLOG(byte[] block) {
3920 int offset = 0;
3921 int todo = block.length;
3922 StringBuilder buf = new StringBuilder(64);
3923 while (todo > 0) {
3924 buf.append(String.format("%04x ", offset));
3925 int numThisLine = (todo > 16) ? 16 : todo;
3926 for (int i = 0; i < numThisLine; i++) {
3927 buf.append(String.format("%02x ", block[offset+i]));
3928 }
3929 Slog.i("hexdump", buf.toString());
3930 buf.setLength(0);
3931 todo -= numThisLine;
3932 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003933 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003934 }
3935
Christopher Tate6853fcf2011-08-10 17:52:21 -07003936 // Read exactly the given number of bytes into a buffer at the stated offset.
3937 // Returns false if EOF is encountered before the requested number of bytes
3938 // could be read.
3939 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3940 throws IOException {
3941 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3942
3943 int soFar = 0;
3944 while (soFar < size) {
3945 int nRead = in.read(buffer, offset + soFar, size - soFar);
3946 if (nRead <= 0) {
3947 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3948 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003949 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003950 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003951 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003952 return soFar;
3953 }
3954
3955 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3956 final int got = readExactly(instream, block, 0, 512);
3957 if (got == 0) return false; // Clean EOF
3958 if (got < 512) throw new IOException("Unable to read full block header");
3959 mBytes += 512;
3960 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003961 }
3962
3963 // overwrites 'info' fields based on the pax extended header
3964 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3965 throws IOException {
3966 // We should never see a pax extended header larger than this
3967 if (info.size > 32*1024) {
3968 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3969 + " - aborting");
3970 throw new IOException("Sanity failure: pax header size " + info.size);
3971 }
3972
3973 // read whole blocks, not just the content size
3974 int numBlocks = (int)((info.size + 511) >> 9);
3975 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003976 if (readExactly(instream, data, 0, data.length) < data.length) {
3977 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003978 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003979 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003980
3981 final int contentSize = (int) info.size;
3982 int offset = 0;
3983 do {
3984 // extract the line at 'offset'
3985 int eol = offset+1;
3986 while (eol < contentSize && data[eol] != ' ') eol++;
3987 if (eol >= contentSize) {
3988 // error: we just hit EOD looking for the end of the size field
3989 throw new IOException("Invalid pax data");
3990 }
3991 // eol points to the space between the count and the key
3992 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3993 int key = eol + 1; // start of key=value
3994 eol = offset + linelen - 1; // trailing LF
3995 int value;
3996 for (value = key+1; data[value] != '=' && value <= eol; value++);
3997 if (value > eol) {
3998 throw new IOException("Invalid pax declaration");
3999 }
4000
4001 // pax requires that key/value strings be in UTF-8
4002 String keyStr = new String(data, key, value-key, "UTF-8");
4003 // -1 to strip the trailing LF
4004 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4005
4006 if ("path".equals(keyStr)) {
4007 info.path = valStr;
4008 } else if ("size".equals(keyStr)) {
4009 info.size = Long.parseLong(valStr);
4010 } else {
4011 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4012 }
4013
4014 offset += linelen;
4015 } while (offset < contentSize);
4016
4017 return true;
4018 }
4019
4020 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4021 throws IOException {
4022 long value = 0;
4023 final int end = offset + maxChars;
4024 for (int i = offset; i < end; i++) {
4025 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004026 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004027 if (b == 0 || b == ' ') break;
4028 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004029 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004030 }
4031 value = radix * value + (b - '0');
4032 }
4033 return value;
4034 }
4035
4036 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4037 final int end = offset + maxChars;
4038 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004039 // tar string fields terminate early with a NUL
4040 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004041 return new String(data, offset, eos-offset, "US-ASCII");
4042 }
4043
4044 void sendStartRestore() {
4045 if (mObserver != null) {
4046 try {
4047 mObserver.onStartRestore();
4048 } catch (RemoteException e) {
4049 Slog.w(TAG, "full restore observer went away: startRestore");
4050 mObserver = null;
4051 }
4052 }
4053 }
4054
4055 void sendOnRestorePackage(String name) {
4056 if (mObserver != null) {
4057 try {
4058 // TODO: use a more user-friendly name string
4059 mObserver.onRestorePackage(name);
4060 } catch (RemoteException e) {
4061 Slog.w(TAG, "full restore observer went away: restorePackage");
4062 mObserver = null;
4063 }
4064 }
4065 }
4066
4067 void sendEndRestore() {
4068 if (mObserver != null) {
4069 try {
4070 mObserver.onEndRestore();
4071 } catch (RemoteException e) {
4072 Slog.w(TAG, "full restore observer went away: endRestore");
4073 mObserver = null;
4074 }
4075 }
4076 }
4077 }
4078
Christopher Tatedf01dea2009-06-09 20:45:02 -07004079 // ----- Restore handling -----
4080
Christopher Tate78dd4a72009-11-04 11:49:08 -08004081 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4082 // If the target resides on the system partition, we allow it to restore
4083 // data from the like-named package in a restore set even if the signatures
4084 // do not match. (Unlike general applications, those flashed to the system
4085 // partition will be signed with the device's platform certificate, so on
4086 // different phones the same system app will have different signatures.)
4087 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004088 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004089 return true;
4090 }
4091
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004092 // Allow unsigned apps, but not signed on one device and unsigned on the other
4093 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004094 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004095 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004096 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004097 if ((storedSigs == null || storedSigs.length == 0)
4098 && (deviceSigs == null || deviceSigs.length == 0)) {
4099 return true;
4100 }
4101 if (storedSigs == null || deviceSigs == null) {
4102 return false;
4103 }
4104
Christopher Tateabce4e82009-06-18 18:35:32 -07004105 // !!! TODO: this demands that every stored signature match one
4106 // that is present on device, and does not demand the converse.
4107 // Is this this right policy?
4108 int nStored = storedSigs.length;
4109 int nDevice = deviceSigs.length;
4110
4111 for (int i=0; i < nStored; i++) {
4112 boolean match = false;
4113 for (int j=0; j < nDevice; j++) {
4114 if (storedSigs[i].equals(deviceSigs[j])) {
4115 match = true;
4116 break;
4117 }
4118 }
4119 if (!match) {
4120 return false;
4121 }
4122 }
4123 return true;
4124 }
4125
Christopher Tate2982d062011-09-06 20:35:24 -07004126 enum RestoreState {
4127 INITIAL,
4128 DOWNLOAD_DATA,
4129 PM_METADATA,
4130 RUNNING_QUEUE,
4131 FINAL
4132 }
4133
4134 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004135 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004136 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004137 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004138 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004139 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004140 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004141 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004142 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004143 private long mStartRealtime;
4144 private PackageManagerBackupAgent mPmAgent;
4145 private List<PackageInfo> mAgentPackages;
4146 private ArrayList<PackageInfo> mRestorePackages;
4147 private RestoreState mCurrentState;
4148 private int mCount;
4149 private boolean mFinished;
4150 private int mStatus;
4151 private File mBackupDataName;
4152 private File mNewStateName;
4153 private File mSavedStateName;
4154 private ParcelFileDescriptor mBackupData;
4155 private ParcelFileDescriptor mNewState;
4156 private PackageInfo mCurrentPackage;
4157
Christopher Tatedf01dea2009-06-09 20:45:02 -07004158
Christopher Tate5cbbf562009-06-22 16:44:51 -07004159 class RestoreRequest {
4160 public PackageInfo app;
4161 public int storedAppVersion;
4162
4163 RestoreRequest(PackageInfo _app, int _version) {
4164 app = _app;
4165 storedAppVersion = _version;
4166 }
4167 }
4168
Christopher Tate44a27902010-01-27 17:15:49 -08004169 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004170 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004171 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004172 mCurrentState = RestoreState.INITIAL;
4173 mFinished = false;
4174 mPmAgent = null;
4175
Christopher Tatedf01dea2009-06-09 20:45:02 -07004176 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004177 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004178 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004179 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004180 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004181 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004182
Christopher Tate284f1bb2011-07-07 14:31:18 -07004183 if (filterSet != null) {
4184 mFilterSet = new HashSet<String>();
4185 for (String pkg : filterSet) {
4186 mFilterSet.add(pkg);
4187 }
4188 } else {
4189 mFilterSet = null;
4190 }
4191
Christopher Tate5cb400b2009-06-25 16:03:14 -07004192 try {
4193 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4194 } catch (RemoteException e) {
4195 // can't happen; the transport is local
4196 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004197 }
4198
Christopher Tate2982d062011-09-06 20:35:24 -07004199 // Execute one tick of whatever state machine the task implements
4200 @Override
4201 public void execute() {
4202 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4203 switch (mCurrentState) {
4204 case INITIAL:
4205 beginRestore();
4206 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004207
Christopher Tate2982d062011-09-06 20:35:24 -07004208 case DOWNLOAD_DATA:
4209 downloadRestoreData();
4210 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004211
Christopher Tate2982d062011-09-06 20:35:24 -07004212 case PM_METADATA:
4213 restorePmMetadata();
4214 break;
4215
4216 case RUNNING_QUEUE:
4217 restoreNextAgent();
4218 break;
4219
4220 case FINAL:
4221 if (!mFinished) finalizeRestore();
4222 else {
4223 Slog.e(TAG, "Duplicate finish");
4224 }
4225 mFinished = true;
4226 break;
4227 }
4228 }
4229
4230 // Initialize and set up for the PM metadata restore, which comes first
4231 void beginRestore() {
4232 // Don't account time doing the restore as inactivity of the app
4233 // that has opened a restore session.
4234 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4235
4236 // Assume error until we successfully init everything
4237 mStatus = BackupConstants.TRANSPORT_ERROR;
4238
Christopher Tatedf01dea2009-06-09 20:45:02 -07004239 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004240 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004241 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004242
Dan Egnorefe52642009-06-24 00:16:33 -07004243 // Get the list of all packages which have backup enabled.
4244 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004245 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004246 PackageInfo omPackage = new PackageInfo();
4247 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004248 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004249
Christopher Tate2982d062011-09-06 20:35:24 -07004250 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004251 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004252 // if there's a filter set, strip out anything that isn't
4253 // present before proceeding
4254 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004255 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4256 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004257 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004258 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004259 }
4260 }
Christopher Tate2982d062011-09-06 20:35:24 -07004261 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004262 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004263 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004264 Slog.i(TAG, " " + p);
4265 }
4266 }
4267 }
Christopher Tate2982d062011-09-06 20:35:24 -07004268 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004269 } else {
4270 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004271 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004272 }
Dan Egnorefe52642009-06-24 00:16:33 -07004273
Christopher Tate7d562ec2009-06-25 18:03:43 -07004274 // let the observer know that we're running
4275 if (mObserver != null) {
4276 try {
4277 // !!! TODO: get an actual count from the transport after
4278 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004279 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004280 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004281 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004282 mObserver = null;
4283 }
4284 }
Christopher Tate2982d062011-09-06 20:35:24 -07004285 } catch (RemoteException e) {
4286 // Something has gone catastrophically wrong with the transport
4287 Slog.e(TAG, "Error communicating with transport for restore");
4288 executeNextState(RestoreState.FINAL);
4289 return;
4290 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004291
Christopher Tate2982d062011-09-06 20:35:24 -07004292 mStatus = BackupConstants.TRANSPORT_OK;
4293 executeNextState(RestoreState.DOWNLOAD_DATA);
4294 }
4295
4296 void downloadRestoreData() {
4297 // Note that the download phase can be very time consuming, but we're executing
4298 // it inline here on the looper. This is "okay" because it is not calling out to
4299 // third party code; the transport is "trusted," and so we assume it is being a
4300 // good citizen and timing out etc when appropriate.
4301 //
4302 // TODO: when appropriate, move the download off the looper and rearrange the
4303 // error handling around that.
4304 try {
4305 mStatus = mTransport.startRestore(mToken,
4306 mRestorePackages.toArray(new PackageInfo[0]));
4307 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004308 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004309 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004310 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004311 return;
4312 }
Christopher Tate2982d062011-09-06 20:35:24 -07004313 } catch (RemoteException e) {
4314 Slog.e(TAG, "Error communicating with transport for restore");
4315 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4316 mStatus = BackupConstants.TRANSPORT_ERROR;
4317 executeNextState(RestoreState.FINAL);
4318 return;
4319 }
Dan Egnorefe52642009-06-24 00:16:33 -07004320
Christopher Tate2982d062011-09-06 20:35:24 -07004321 // Successful download of the data to be parceled out to the apps, so off we go.
4322 executeNextState(RestoreState.PM_METADATA);
4323 }
4324
4325 void restorePmMetadata() {
4326 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004327 String packageName = mTransport.nextRestorePackage();
4328 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004329 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004330 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004331 mStatus = BackupConstants.TRANSPORT_ERROR;
4332 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004333 return;
4334 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004335 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004336 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004337 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004338 mStatus = BackupConstants.TRANSPORT_OK;
4339 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004340 return;
4341 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004342 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004343 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004344 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004345 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004346 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004347 return;
4348 }
4349
4350 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004351 PackageInfo omPackage = new PackageInfo();
4352 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4353 mPmAgent = new PackageManagerBackupAgent(
4354 mPackageManager, mAgentPackages);
4355 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004356 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004357 // The PM agent called operationComplete() already, because our invocation
4358 // of it is process-local and therefore synchronous. That means that a
4359 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4360 // proceed with running the queue do we remove that pending message and
4361 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004362
Christopher Tate8c032472009-07-02 14:28:47 -07004363 // Verify that the backup set includes metadata. If not, we can't do
4364 // signature/version verification etc, so we simply do not proceed with
4365 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004366 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004367 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004368 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004369 "Package manager restore metadata missing");
4370 mStatus = BackupConstants.TRANSPORT_ERROR;
4371 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4372 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004373 return;
4374 }
Christopher Tate2982d062011-09-06 20:35:24 -07004375 } catch (RemoteException e) {
4376 Slog.e(TAG, "Error communicating with transport for restore");
4377 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4378 mStatus = BackupConstants.TRANSPORT_ERROR;
4379 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4380 executeNextState(RestoreState.FINAL);
4381 return;
4382 }
Christopher Tate8c032472009-07-02 14:28:47 -07004383
Christopher Tate2982d062011-09-06 20:35:24 -07004384 // Metadata is intact, so we can now run the restore queue. If we get here,
4385 // we have already enqueued the necessary next-step message on the looper.
4386 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004387
Christopher Tate2982d062011-09-06 20:35:24 -07004388 void restoreNextAgent() {
4389 try {
4390 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004391
Christopher Tate2982d062011-09-06 20:35:24 -07004392 if (packageName == null) {
4393 Slog.e(TAG, "Error getting next restore package");
4394 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4395 executeNextState(RestoreState.FINAL);
4396 return;
4397 } else if (packageName.equals("")) {
4398 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4399 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4400 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4401 executeNextState(RestoreState.FINAL);
4402 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004403 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004404
4405 if (mObserver != null) {
4406 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004407 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004408 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004409 Slog.d(TAG, "Restore observer died in onUpdate");
4410 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004411 }
4412 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004413
Christopher Tate2982d062011-09-06 20:35:24 -07004414 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4415 if (metaInfo == null) {
4416 Slog.e(TAG, "Missing metadata for " + packageName);
4417 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4418 "Package metadata missing");
4419 executeNextState(RestoreState.RUNNING_QUEUE);
4420 return;
Christopher Tate84725812010-02-04 15:52:40 -08004421 }
4422
Christopher Tate2982d062011-09-06 20:35:24 -07004423 PackageInfo packageInfo;
4424 try {
4425 int flags = PackageManager.GET_SIGNATURES;
4426 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4427 } catch (NameNotFoundException e) {
4428 Slog.e(TAG, "Invalid package restoring data", e);
4429 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4430 "Package missing on device");
4431 executeNextState(RestoreState.RUNNING_QUEUE);
4432 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004433 }
4434
Christopher Tatee7287a02012-09-07 18:32:12 -07004435 if (packageInfo.applicationInfo.backupAgentName == null
4436 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4437 if (DEBUG) {
4438 Slog.i(TAG, "Data exists for package " + packageName
4439 + " but app has no agent; skipping");
4440 }
4441 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4442 "Package has no agent");
4443 executeNextState(RestoreState.RUNNING_QUEUE);
4444 return;
4445 }
4446
Christopher Tate2982d062011-09-06 20:35:24 -07004447 if (metaInfo.versionCode > packageInfo.versionCode) {
4448 // Data is from a "newer" version of the app than we have currently
4449 // installed. If the app has not declared that it is prepared to
4450 // handle this case, we do not attempt the restore.
4451 if ((packageInfo.applicationInfo.flags
4452 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4453 String message = "Version " + metaInfo.versionCode
4454 + " > installed version " + packageInfo.versionCode;
4455 Slog.w(TAG, "Package " + packageName + ": " + message);
4456 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4457 packageName, message);
4458 executeNextState(RestoreState.RUNNING_QUEUE);
4459 return;
4460 } else {
4461 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4462 + " > installed " + packageInfo.versionCode
4463 + " but restoreAnyVersion");
4464 }
4465 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004466
Christopher Tate2982d062011-09-06 20:35:24 -07004467 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4468 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4469 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4470 "Signature mismatch");
4471 executeNextState(RestoreState.RUNNING_QUEUE);
4472 return;
4473 }
4474
4475 if (DEBUG) Slog.v(TAG, "Package " + packageName
4476 + " restore version [" + metaInfo.versionCode
4477 + "] is compatible with installed version ["
4478 + packageInfo.versionCode + "]");
4479
4480 // Then set up and bind the agent
4481 IBackupAgent agent = bindToAgentSynchronous(
4482 packageInfo.applicationInfo,
4483 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4484 if (agent == null) {
4485 Slog.w(TAG, "Can't find backup agent for " + packageName);
4486 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4487 "Restore agent missing");
4488 executeNextState(RestoreState.RUNNING_QUEUE);
4489 return;
4490 }
4491
4492 // And then finally start the restore on this agent
4493 try {
4494 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4495 ++mCount;
4496 } catch (Exception e) {
4497 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4498 agentErrorCleanup();
4499 executeNextState(RestoreState.RUNNING_QUEUE);
4500 }
4501 } catch (RemoteException e) {
4502 Slog.e(TAG, "Unable to fetch restore data from transport");
4503 mStatus = BackupConstants.TRANSPORT_ERROR;
4504 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004505 }
4506 }
4507
Christopher Tate2982d062011-09-06 20:35:24 -07004508 void finalizeRestore() {
4509 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4510
4511 try {
4512 mTransport.finishRestore();
4513 } catch (RemoteException e) {
4514 Slog.e(TAG, "Error finishing restore", e);
4515 }
4516
4517 if (mObserver != null) {
4518 try {
4519 mObserver.restoreFinished(mStatus);
4520 } catch (RemoteException e) {
4521 Slog.d(TAG, "Restore observer died at restoreFinished");
4522 }
4523 }
4524
4525 // If this was a restoreAll operation, record that this was our
4526 // ancestral dataset, as well as the set of apps that are possibly
4527 // restoreable from the dataset
4528 if (mTargetPackage == null && mPmAgent != null) {
4529 mAncestralPackages = mPmAgent.getRestoredPackages();
4530 mAncestralToken = mToken;
4531 writeRestoreTokens();
4532 }
4533
4534 // We must under all circumstances tell the Package Manager to
4535 // proceed with install notifications if it's waiting for us.
4536 if (mPmToken > 0) {
4537 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4538 try {
4539 mPackageManagerBinder.finishPackageInstall(mPmToken);
4540 } catch (RemoteException e) { /* can't happen */ }
4541 }
4542
4543 // Furthermore we need to reset the session timeout clock
4544 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4545 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4546 TIMEOUT_RESTORE_INTERVAL);
4547
4548 // done; we can finally release the wakelock
4549 Slog.i(TAG, "Restore complete.");
4550 mWakelock.release();
4551 }
4552
4553 // Call asynchronously into the app, passing it the restore data. The next step
4554 // after this is always a callback, either operationComplete() or handleTimeout().
4555 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004556 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004557 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004558 final String packageName = app.packageName;
4559
Christopher Tate2982d062011-09-06 20:35:24 -07004560 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004561
Christopher Tatec7b31e32009-06-10 15:49:30 -07004562 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004563 mBackupDataName = new File(mDataDir, packageName + ".restore");
4564 mNewStateName = new File(mStateDir, packageName + ".new");
4565 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004566
Christopher Tate4a627c72011-04-01 14:43:32 -07004567 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004568 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004569 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004570 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004571 ParcelFileDescriptor.MODE_READ_WRITE |
4572 ParcelFileDescriptor.MODE_CREATE |
4573 ParcelFileDescriptor.MODE_TRUNCATE);
4574
Christopher Tate2982d062011-09-06 20:35:24 -07004575 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004576 // Transport-level failure, so we wind everything up and
4577 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004578 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004579 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004580 mBackupData.close();
4581 mBackupDataName.delete();
4582 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004583 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004584 }
4585
4586 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004587 mBackupData.close();
4588 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004589 ParcelFileDescriptor.MODE_READ_ONLY);
4590
Christopher Tate2982d062011-09-06 20:35:24 -07004591 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004592 ParcelFileDescriptor.MODE_READ_WRITE |
4593 ParcelFileDescriptor.MODE_CREATE |
4594 ParcelFileDescriptor.MODE_TRUNCATE);
4595
Christopher Tate44a27902010-01-27 17:15:49 -08004596 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004597 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4598 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004599 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004600 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004601 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004602 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004603
Christopher Tate2982d062011-09-06 20:35:24 -07004604 // After a restore failure we go back to running the queue. If there
4605 // are no more packages to be restored that will be handled by the
4606 // next step.
4607 executeNextState(RestoreState.RUNNING_QUEUE);
4608 }
4609 }
Chris Tate249345b2010-10-29 12:57:04 -07004610
Christopher Tate2982d062011-09-06 20:35:24 -07004611 void agentErrorCleanup() {
4612 // If the agent fails restore, it might have put the app's data
4613 // into an incoherent state. For consistency we wipe its data
4614 // again in this case before continuing with normal teardown
4615 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4616 agentCleanup();
4617 }
4618
4619 void agentCleanup() {
4620 mBackupDataName.delete();
4621 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4622 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4623 mBackupData = mNewState = null;
4624
4625 // if everything went okay, remember the recorded state now
4626 //
4627 // !!! TODO: the restored data should be migrated on the server
4628 // side into the current dataset. In that case the new state file
4629 // we just created would reflect the data already extant in the
4630 // backend, so there'd be nothing more to do. Until that happens,
4631 // however, we need to make sure that we record the data to the
4632 // current backend dataset. (Yes, this means shipping the data over
4633 // the wire in both directions. That's bad, but consistency comes
4634 // first, then efficiency.) Once we introduce server-side data
4635 // migration to the newly-restored device's dataset, we will change
4636 // the following from a discard of the newly-written state to the
4637 // "correct" operation of renaming into the canonical state blob.
4638 mNewStateName.delete(); // TODO: remove; see above comment
4639 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4640
4641 // If this wasn't the PM pseudopackage, tear down the agent side
4642 if (mCurrentPackage.applicationInfo != null) {
4643 // unbind and tidy up even on timeout or failure
4644 try {
4645 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4646
4647 // The agent was probably running with a stub Application object,
4648 // which isn't a valid run mode for the main app logic. Shut
4649 // down the app so that next time it's launched, it gets the
4650 // usual full initialization. Note that this is only done for
4651 // full-system restores: when a single app has requested a restore,
4652 // it is explicitly not killed following that operation.
4653 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4654 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4655 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4656 + mCurrentPackage.applicationInfo.processName);
4657 mActivityManager.killApplicationProcess(
4658 mCurrentPackage.applicationInfo.processName,
4659 mCurrentPackage.applicationInfo.uid);
4660 }
4661 } catch (RemoteException e) {
4662 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004663 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004664 }
Christopher Tate2982d062011-09-06 20:35:24 -07004665
4666 // The caller is responsible for reestablishing the state machine; our
4667 // responsibility here is to clear the decks for whatever comes next.
4668 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4669 synchronized (mCurrentOpLock) {
4670 mCurrentOperations.clear();
4671 }
4672 }
4673
4674 // A call to agent.doRestore() has been positively acknowledged as complete
4675 @Override
4676 public void operationComplete() {
4677 int size = (int) mBackupDataName.length();
4678 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4679 // Just go back to running the restore queue
4680 agentCleanup();
4681
4682 executeNextState(RestoreState.RUNNING_QUEUE);
4683 }
4684
4685 // A call to agent.doRestore() has timed out
4686 @Override
4687 public void handleTimeout() {
4688 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4689 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4690 mCurrentPackage.packageName, "restore timeout");
4691 // Handle like an agent that threw on invocation: wipe it and go on to the next
4692 agentErrorCleanup();
4693 executeNextState(RestoreState.RUNNING_QUEUE);
4694 }
4695
4696 void executeNextState(RestoreState nextState) {
4697 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4698 + this + " nextState=" + nextState);
4699 mCurrentState = nextState;
4700 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4701 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004702 }
4703 }
4704
Christopher Tate44a27902010-01-27 17:15:49 -08004705 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004706 IBackupTransport mTransport;
4707 PackageInfo mPackage;
4708
Christopher Tate44a27902010-01-27 17:15:49 -08004709 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004710 mTransport = transport;
4711 mPackage = packageInfo;
4712 }
4713
Christopher Tateee0e78a2009-07-02 11:17:03 -07004714 public void run() {
4715 try {
4716 // Clear the on-device backup state to ensure a full backup next time
4717 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4718 File stateFile = new File(stateDir, mPackage.packageName);
4719 stateFile.delete();
4720
4721 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004722 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004723 mTransport.clearBackupData(mPackage);
4724 } catch (RemoteException e) {
4725 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004726 } catch (Exception e) {
4727 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004728 } finally {
4729 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004730 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004731 mTransport.finishBackup();
4732 } catch (RemoteException e) {
4733 // can't happen; the transport is local
4734 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004735
4736 // Last but not least, release the cpu
4737 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004738 }
4739 }
4740 }
4741
Christopher Tate44a27902010-01-27 17:15:49 -08004742 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004743 HashSet<String> mQueue;
4744
Christopher Tate44a27902010-01-27 17:15:49 -08004745 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004746 mQueue = transportNames;
4747 }
4748
Christopher Tate4cc86e12009-09-21 19:36:51 -07004749 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004750 try {
4751 for (String transportName : mQueue) {
4752 IBackupTransport transport = getTransport(transportName);
4753 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004754 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004755 continue;
4756 }
4757
Joe Onorato8a9b2202010-02-26 18:56:32 -08004758 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004759 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004760 long startRealtime = SystemClock.elapsedRealtime();
4761 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004762
Christopher Tate4cc86e12009-09-21 19:36:51 -07004763 if (status == BackupConstants.TRANSPORT_OK) {
4764 status = transport.finishBackup();
4765 }
4766
4767 // Okay, the wipe really happened. Clean up our local bookkeeping.
4768 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004769 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004770 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004771 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004772 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004773 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004774 synchronized (mQueueLock) {
4775 recordInitPendingLocked(false, transportName);
4776 }
Dan Egnor726247c2009-09-29 19:12:31 -07004777 } else {
4778 // If this didn't work, requeue this one and try again
4779 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004780 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004781 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004782 synchronized (mQueueLock) {
4783 recordInitPendingLocked(true, transportName);
4784 }
4785 // do this via another alarm to make sure of the wakelock states
4786 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004787 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004788 + transportName + " resched in " + delay);
4789 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4790 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004791 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004792 }
4793 } catch (RemoteException e) {
4794 // can't happen; the transports are local
4795 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004796 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004797 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004798 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004799 mWakelock.release();
4800 }
4801 }
4802 }
4803
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004804 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004805 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004806 dataChangedImpl(packageName, targets);
4807 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004808
Christopher Tatea3d55342012-03-27 13:16:18 -07004809 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004810 // Record that we need a backup pass for the caller. Since multiple callers
4811 // may share a uid, we need to note all candidates within that uid and schedule
4812 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004813 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004814
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004815 if (targets == null) {
4816 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4817 + " uid=" + Binder.getCallingUid());
4818 return;
4819 }
4820
4821 synchronized (mQueueLock) {
4822 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004823 if (targets.contains(packageName)) {
4824 // Add the caller to the set of pending backups. If there is
4825 // one already there, then overwrite it, but no harm done.
4826 BackupRequest req = new BackupRequest(packageName);
4827 if (mPendingBackups.put(packageName, req) == null) {
4828 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004829
Christopher Tatea3d55342012-03-27 13:16:18 -07004830 // Journal this request in case of crash. The put()
4831 // operation returned null when this package was not already
4832 // in the set; we want to avoid touching the disk redundantly.
4833 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004834
Christopher Tatea3d55342012-03-27 13:16:18 -07004835 if (MORE_DEBUG) {
4836 int numKeys = mPendingBackups.size();
4837 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4838 for (BackupRequest b : mPendingBackups.values()) {
4839 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004840 }
4841 }
4842 }
4843 }
4844 }
4845 }
4846
4847 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004848 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004849 // If the caller does not hold the BACKUP permission, it can only request a
4850 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004851 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004852 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004853 synchronized (mBackupParticipants) {
4854 return mBackupParticipants.get(Binder.getCallingUid());
4855 }
4856 }
4857
4858 // a caller with full permission can ask to back up any participating app
4859 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004860 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004861 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004862 int N = mBackupParticipants.size();
4863 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004864 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004865 if (s != null) {
4866 targets.addAll(s);
4867 }
4868 }
4869 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004870 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004871 }
Christopher Tate46758122009-05-06 11:22:00 -07004872
Christopher Tatecde87f42009-06-12 12:55:53 -07004873 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004874 RandomAccessFile out = null;
4875 try {
4876 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4877 out = new RandomAccessFile(mJournal, "rws");
4878 out.seek(out.length());
4879 out.writeUTF(str);
4880 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004881 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004882 mJournal = null;
4883 } finally {
4884 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004885 }
4886 }
4887
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004888 // ----- IBackupManager binder interface -----
4889
4890 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004891 final int callingUserHandle = UserHandle.getCallingUserId();
4892 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004893 // App is running under a non-owner user profile. For now, we do not back
4894 // up data from secondary user profiles.
4895 // TODO: backups for all user profiles.
4896 if (MORE_DEBUG) {
4897 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4898 + callingUserHandle);
4899 }
4900 return;
4901 }
4902
Christopher Tatea3d55342012-03-27 13:16:18 -07004903 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004904 if (targets == null) {
4905 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4906 + " uid=" + Binder.getCallingUid());
4907 return;
4908 }
4909
4910 mBackupHandler.post(new Runnable() {
4911 public void run() {
4912 dataChangedImpl(packageName, targets);
4913 }
4914 });
4915 }
4916
Christopher Tateee0e78a2009-07-02 11:17:03 -07004917 // Clear the given package's backup data from the current transport
4918 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004919 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004920 PackageInfo info;
4921 try {
4922 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4923 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004924 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004925 return;
4926 }
4927
4928 // If the caller does not hold the BACKUP permission, it can only request a
4929 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004930 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004931 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004932 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4933 apps = mBackupParticipants.get(Binder.getCallingUid());
4934 } else {
4935 // a caller with full permission can ask to back up any participating app
4936 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004937 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004938 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004939 int N = mBackupParticipants.size();
4940 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004941 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004942 if (s != null) {
4943 apps.addAll(s);
4944 }
4945 }
4946 }
4947
Christopher Tatea3d55342012-03-27 13:16:18 -07004948 // Is the given app an available participant?
4949 if (apps.contains(packageName)) {
4950 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4951 // found it; fire off the clear request
4952 synchronized (mQueueLock) {
4953 long oldId = Binder.clearCallingIdentity();
4954 mWakelock.acquire();
4955 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4956 new ClearParams(getTransport(mCurrentTransport), info));
4957 mBackupHandler.sendMessage(msg);
4958 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004959 }
4960 }
4961 }
4962
Christopher Tateace7f092009-06-15 18:07:25 -07004963 // Run a backup pass immediately for any applications that have declared
4964 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004965 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004966 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004967
Joe Onorato8a9b2202010-02-26 18:56:32 -08004968 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004969 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004970 // Because the alarms we are using can jitter, and we want an *immediate*
4971 // backup pass to happen, we restart the timer beginning with "next time,"
4972 // then manually fire the backup trigger intent ourselves.
4973 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004974 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004975 mRunBackupIntent.send();
4976 } catch (PendingIntent.CanceledException e) {
4977 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004978 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004979 }
Christopher Tate46758122009-05-06 11:22:00 -07004980 }
4981 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004982
Christopher Tated2c0cd42011-09-15 15:51:29 -07004983 boolean deviceIsProvisioned() {
4984 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07004985 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004986 }
4987
Christopher Tate4a627c72011-04-01 14:43:32 -07004988 // Run a *full* backup pass for the given package, writing the resulting data stream
4989 // to the supplied file descriptor. This method is synchronous and does not return
4990 // to the caller until the backup has been completed.
4991 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004992 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004993 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4994
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004995 final int callingUserHandle = UserHandle.getCallingUserId();
4996 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004997 throw new IllegalStateException("Backup supported only for the device owner");
4998 }
4999
Christopher Tate4a627c72011-04-01 14:43:32 -07005000 // Validate
5001 if (!doAllApps) {
5002 if (!includeShared) {
5003 // If we're backing up shared data (sdcard or equivalent), then we can run
5004 // without any supplied app names. Otherwise, we'd be doing no work, so
5005 // report the error.
5006 if (pkgList == null || pkgList.length == 0) {
5007 throw new IllegalArgumentException(
5008 "Backup requested but neither shared nor any apps named");
5009 }
5010 }
5011 }
5012
Christopher Tate4a627c72011-04-01 14:43:32 -07005013 long oldId = Binder.clearCallingIdentity();
5014 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005015 // Doesn't make sense to do a full backup prior to setup
5016 if (!deviceIsProvisioned()) {
5017 Slog.i(TAG, "Full backup not supported before setup");
5018 return;
5019 }
5020
5021 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5022 + " shared=" + includeShared + " all=" + doAllApps
5023 + " pkgs=" + pkgList);
5024 Slog.i(TAG, "Beginning full backup...");
5025
Christopher Tate4a627c72011-04-01 14:43:32 -07005026 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005027 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005028 final int token = generateToken();
5029 synchronized (mFullConfirmations) {
5030 mFullConfirmations.put(token, params);
5031 }
5032
Christopher Tate75a99702011-05-18 16:28:19 -07005033 // start up the confirmation UI
5034 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5035 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5036 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005037 mFullConfirmations.delete(token);
5038 return;
5039 }
Christopher Tate75a99702011-05-18 16:28:19 -07005040
5041 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005042 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5043
5044 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005045 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005046
5047 // wait for the backup to be performed
5048 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5049 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005050 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005051 try {
5052 fd.close();
5053 } catch (IOException e) {
5054 // just eat it
5055 }
Christopher Tate75a99702011-05-18 16:28:19 -07005056 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005057 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005058 }
Christopher Tate75a99702011-05-18 16:28:19 -07005059 }
5060
5061 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005062 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005063
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005064 final int callingUserHandle = UserHandle.getCallingUserId();
5065 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005066 throw new IllegalStateException("Restore supported only for the device owner");
5067 }
5068
Christopher Tate75a99702011-05-18 16:28:19 -07005069 long oldId = Binder.clearCallingIdentity();
5070
5071 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005072 // Check whether the device has been provisioned -- we don't handle
5073 // full restores prior to completing the setup process.
5074 if (!deviceIsProvisioned()) {
5075 Slog.i(TAG, "Full restore not permitted before setup");
5076 return;
5077 }
5078
5079 Slog.i(TAG, "Beginning full restore...");
5080
Christopher Tate75a99702011-05-18 16:28:19 -07005081 FullRestoreParams params = new FullRestoreParams(fd);
5082 final int token = generateToken();
5083 synchronized (mFullConfirmations) {
5084 mFullConfirmations.put(token, params);
5085 }
5086
5087 // start up the confirmation UI
5088 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5089 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5090 Slog.e(TAG, "Unable to launch full restore confirmation");
5091 mFullConfirmations.delete(token);
5092 return;
5093 }
5094
5095 // make sure the screen is lit for the user interaction
5096 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5097
5098 // start the confirmation countdown
5099 startConfirmationTimeout(token, params);
5100
5101 // wait for the restore to be performed
5102 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5103 waitForCompletion(params);
5104 } finally {
5105 try {
5106 fd.close();
5107 } catch (IOException e) {
5108 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5109 }
5110 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005111 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005112 }
5113 }
5114
5115 boolean startConfirmationUi(int token, String action) {
5116 try {
5117 Intent confIntent = new Intent(action);
5118 confIntent.setClassName("com.android.backupconfirm",
5119 "com.android.backupconfirm.BackupRestoreConfirmation");
5120 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5121 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5122 mContext.startActivity(confIntent);
5123 } catch (ActivityNotFoundException e) {
5124 return false;
5125 }
5126 return true;
5127 }
5128
5129 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005130 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005131 + TIMEOUT_FULL_CONFIRMATION + " millis");
5132 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5133 token, 0, params);
5134 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005135 }
5136
5137 void waitForCompletion(FullParams params) {
5138 synchronized (params.latch) {
5139 while (params.latch.get() == false) {
5140 try {
5141 params.latch.wait();
5142 } catch (InterruptedException e) { /* never interrupted */ }
5143 }
5144 }
5145 }
5146
5147 void signalFullBackupRestoreCompletion(FullParams params) {
5148 synchronized (params.latch) {
5149 params.latch.set(true);
5150 params.latch.notifyAll();
5151 }
5152 }
5153
5154 // Confirm that the previously-requested full backup/restore operation can proceed. This
5155 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005156 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005157 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005158 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005159 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5160 + " allow=" + allow);
5161
5162 // TODO: possibly require not just this signature-only permission, but even
5163 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005164 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005165
5166 long oldId = Binder.clearCallingIdentity();
5167 try {
5168
5169 FullParams params;
5170 synchronized (mFullConfirmations) {
5171 params = mFullConfirmations.get(token);
5172 if (params != null) {
5173 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5174 mFullConfirmations.delete(token);
5175
5176 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005177 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005178 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005179 : MSG_RUN_FULL_RESTORE;
5180
Christopher Tate728a1c42011-07-28 18:03:03 -07005181 params.observer = observer;
5182 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005183
5184 boolean isEncrypted;
5185 try {
5186 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5187 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5188 } catch (RemoteException e) {
5189 // couldn't contact the mount service; fail "safe" and assume encryption
5190 Slog.e(TAG, "Unable to contact mount service!");
5191 isEncrypted = true;
5192 }
5193 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005194
Christopher Tate75a99702011-05-18 16:28:19 -07005195 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005196 mWakelock.acquire();
5197 Message msg = mBackupHandler.obtainMessage(verb, params);
5198 mBackupHandler.sendMessage(msg);
5199 } else {
5200 Slog.w(TAG, "User rejected full backup/restore operation");
5201 // indicate completion without having actually transferred any data
5202 signalFullBackupRestoreCompletion(params);
5203 }
5204 } else {
5205 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5206 }
5207 }
5208 } finally {
5209 Binder.restoreCallingIdentity(oldId);
5210 }
5211 }
5212
Christopher Tate8031a3d2009-07-06 16:36:05 -07005213 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005214 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005215 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005216 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005217
Joe Onorato8a9b2202010-02-26 18:56:32 -08005218 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005219
Christopher Tate6ef58a12009-06-29 14:56:28 -07005220 boolean wasEnabled = mEnabled;
5221 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005222 Settings.Secure.putInt(mContext.getContentResolver(),
5223 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005224 mEnabled = enable;
5225 }
5226
Christopher Tate49401dd2009-07-01 12:34:29 -07005227 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005228 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005229 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005230 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005231 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005232 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005233 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005234
Christopher Tateb6787f22009-07-02 17:40:45 -07005235 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005236
5237 // This also constitutes an opt-out, so we wipe any data for
5238 // this device from the backend. We start that process with
5239 // an alarm in order to guarantee wakelock states.
5240 if (wasEnabled && mProvisioned) {
5241 // NOTE: we currently flush every registered transport, not just
5242 // the currently-active one.
5243 HashSet<String> allTransports;
5244 synchronized (mTransports) {
5245 allTransports = new HashSet<String>(mTransports.keySet());
5246 }
5247 // build the set of transports for which we are posting an init
5248 for (String transport : allTransports) {
5249 recordInitPendingLocked(true, transport);
5250 }
5251 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5252 mRunInitIntent);
5253 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005254 }
5255 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005256 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005257
Christopher Tatecce9da52010-02-03 15:11:15 -08005258 // Enable/disable automatic restore of app data at install time
5259 public void setAutoRestore(boolean doAutoRestore) {
5260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005261 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005262
Joe Onorato8a9b2202010-02-26 18:56:32 -08005263 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005264
5265 synchronized (this) {
5266 Settings.Secure.putInt(mContext.getContentResolver(),
5267 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5268 mAutoRestore = doAutoRestore;
5269 }
5270 }
5271
Christopher Tate8031a3d2009-07-06 16:36:05 -07005272 // Mark the backup service as having been provisioned
5273 public void setBackupProvisioned(boolean available) {
5274 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5275 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005276 /*
5277 * This is now a no-op; provisioning is simply the device's own setup state.
5278 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005279 }
5280
5281 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005282 // We used to use setInexactRepeating(), but that may be linked to
5283 // backups running at :00 more often than not, creating load spikes.
5284 // Schedule at an exact time for now, and also add a bit of "fuzz".
5285
5286 Random random = new Random();
5287 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5288 random.nextInt(FUZZ_MILLIS);
5289 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5290 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005291 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005292 }
5293
Christopher Tate6ef58a12009-06-29 14:56:28 -07005294 // Report whether the backup mechanism is currently enabled
5295 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005296 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005297 return mEnabled; // no need to synchronize just to read it
5298 }
5299
Christopher Tate91717492009-06-26 21:07:13 -07005300 // Report the name of the currently active transport
5301 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005302 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005303 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005304 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005305 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005306 }
5307
Christopher Tate91717492009-06-26 21:07:13 -07005308 // Report all known, available backup transports
5309 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005311
Christopher Tate91717492009-06-26 21:07:13 -07005312 String[] list = null;
5313 ArrayList<String> known = new ArrayList<String>();
5314 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5315 if (entry.getValue() != null) {
5316 known.add(entry.getKey());
5317 }
5318 }
5319
5320 if (known.size() > 0) {
5321 list = new String[known.size()];
5322 known.toArray(list);
5323 }
5324 return list;
5325 }
5326
5327 // Select which transport to use for the next backup operation. If the given
5328 // name is not one of the available transports, no action is taken and the method
5329 // returns null.
5330 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005332
5333 synchronized (mTransports) {
5334 String prevTransport = null;
5335 if (mTransports.get(transport) != null) {
5336 prevTransport = mCurrentTransport;
5337 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005338 Settings.Secure.putString(mContext.getContentResolver(),
5339 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005340 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005341 + " returning " + prevTransport);
5342 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005343 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005344 }
5345 return prevTransport;
5346 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005347 }
5348
Christopher Tatef5e1c292010-12-08 18:40:26 -08005349 // Supply the configuration Intent for the given transport. If the name is not one
5350 // of the available transports, or if the transport does not supply any configuration
5351 // UI, the method returns null.
5352 public Intent getConfigurationIntent(String transportName) {
5353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5354 "getConfigurationIntent");
5355
5356 synchronized (mTransports) {
5357 final IBackupTransport transport = mTransports.get(transportName);
5358 if (transport != null) {
5359 try {
5360 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005361 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005362 + intent);
5363 return intent;
5364 } catch (RemoteException e) {
5365 /* fall through to return null */
5366 }
5367 }
5368 }
5369
5370 return null;
5371 }
5372
5373 // Supply the configuration summary string for the given transport. If the name is
5374 // not one of the available transports, or if the transport does not supply any
5375 // summary / destination string, the method can return null.
5376 //
5377 // This string is used VERBATIM as the summary text of the relevant Settings item!
5378 public String getDestinationString(String transportName) {
5379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005380 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005381
5382 synchronized (mTransports) {
5383 final IBackupTransport transport = mTransports.get(transportName);
5384 if (transport != null) {
5385 try {
5386 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005387 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005388 return text;
5389 } catch (RemoteException e) {
5390 /* fall through to return null */
5391 }
5392 }
5393 }
5394
5395 return null;
5396 }
5397
Christopher Tate043dadc2009-06-02 16:11:00 -07005398 // Callback: a requested backup agent has been instantiated. This should only
5399 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005400 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005401 synchronized(mAgentConnectLock) {
5402 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005403 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005404 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5405 mConnectedAgent = agent;
5406 mConnecting = false;
5407 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005408 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005409 + " claiming agent connected");
5410 }
5411 mAgentConnectLock.notifyAll();
5412 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005413 }
5414
5415 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5416 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005417 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005418 public void agentDisconnected(String packageName) {
5419 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005420 synchronized(mAgentConnectLock) {
5421 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5422 mConnectedAgent = null;
5423 mConnecting = false;
5424 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005425 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005426 + " claiming agent disconnected");
5427 }
5428 mAgentConnectLock.notifyAll();
5429 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005430 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005431
Christopher Tate1bb69062010-02-19 17:02:12 -08005432 // An application being installed will need a restore pass, then the Package Manager
5433 // will need to be told when the restore is finished.
5434 public void restoreAtInstall(String packageName, int token) {
5435 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005436 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005437 + " attemping install-time restore");
5438 return;
5439 }
5440
5441 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005442 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005443 + " token=" + Integer.toHexString(token));
5444
Christopher Tatef0872722010-02-25 15:22:48 -08005445 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005446 // okay, we're going to attempt a restore of this package from this restore set.
5447 // The eventual message back into the Package Manager to run the post-install
5448 // steps for 'token' will be issued from the restore handling code.
5449
5450 // We can use a synthetic PackageInfo here because:
5451 // 1. We know it's valid, since the Package Manager supplied the name
5452 // 2. Only the packageName field will be used by the restore code
5453 PackageInfo pkg = new PackageInfo();
5454 pkg.packageName = packageName;
5455
5456 mWakelock.acquire();
5457 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5458 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005459 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005460 mBackupHandler.sendMessage(msg);
5461 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005462 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5463 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005464 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005465 try {
5466 mPackageManagerBinder.finishPackageInstall(token);
5467 } catch (RemoteException e) { /* can't happen */ }
5468 }
5469 }
5470
Christopher Tate8c850b72009-06-07 19:33:20 -07005471 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005472 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5473 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5474 + " transport=" + transport);
5475
5476 boolean needPermission = true;
5477 if (transport == null) {
5478 transport = mCurrentTransport;
5479
5480 if (packageName != null) {
5481 PackageInfo app = null;
5482 try {
5483 app = mPackageManager.getPackageInfo(packageName, 0);
5484 } catch (NameNotFoundException nnf) {
5485 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5486 throw new IllegalArgumentException("Package " + packageName + " not found");
5487 }
5488
5489 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5490 // So: using the current active transport, and the caller has asked
5491 // that its own package will be restored. In this narrow use case
5492 // we do not require the caller to hold the permission.
5493 needPermission = false;
5494 }
5495 }
5496 }
5497
5498 if (needPermission) {
5499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5500 "beginRestoreSession");
5501 } else {
5502 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5503 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005504
5505 synchronized(this) {
5506 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005507 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005508 return null;
5509 }
Chris Tate44ab8452010-11-16 15:10:49 -08005510 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005511 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005512 }
5513 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005514 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005515
Christopher Tate73a3cb32010-12-13 18:27:26 -08005516 void clearRestoreSession(ActiveRestoreSession currentSession) {
5517 synchronized(this) {
5518 if (currentSession != mActiveRestoreSession) {
5519 Slog.e(TAG, "ending non-current restore session");
5520 } else {
5521 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5522 mActiveRestoreSession = null;
5523 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5524 }
5525 }
5526 }
5527
Christopher Tate44a27902010-01-27 17:15:49 -08005528 // Note that a currently-active backup agent has notified us that it has
5529 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005530 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005531 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005532 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5533 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005534 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005535 op = mCurrentOperations.get(token);
5536 if (op != null) {
5537 op.state = OP_ACKNOWLEDGED;
5538 }
Christopher Tate44a27902010-01-27 17:15:49 -08005539 mCurrentOpLock.notifyAll();
5540 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005541
5542 // The completion callback, if any, is invoked on the handler
5543 if (op != null && op.callback != null) {
5544 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5545 mBackupHandler.sendMessage(msg);
5546 }
Christopher Tate44a27902010-01-27 17:15:49 -08005547 }
5548
Christopher Tate9b3905c2009-06-08 15:24:01 -07005549 // ----- Restore session -----
5550
Christopher Tate80202c82010-01-25 19:37:47 -08005551 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005552 private static final String TAG = "RestoreSession";
5553
Chris Tate44ab8452010-11-16 15:10:49 -08005554 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005555 private IBackupTransport mRestoreTransport = null;
5556 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005557 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005558
Chris Tate44ab8452010-11-16 15:10:49 -08005559 ActiveRestoreSession(String packageName, String transport) {
5560 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005561 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005562 }
5563
5564 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005565 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005567 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005568 if (observer == null) {
5569 throw new IllegalArgumentException("Observer must not be null");
5570 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005571
Christopher Tate73a3cb32010-12-13 18:27:26 -08005572 if (mEnded) {
5573 throw new IllegalStateException("Restore session already ended");
5574 }
5575
Christopher Tate1bb69062010-02-19 17:02:12 -08005576 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005577 try {
Christopher Tate43383042009-07-13 15:17:13 -07005578 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005579 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005580 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005581 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005582 // spin off the transport request to our service thread
5583 mWakelock.acquire();
5584 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5585 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5586 mBackupHandler.sendMessage(msg);
5587 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005588 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005589 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005590 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005591 } finally {
5592 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005593 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005594 }
5595
Christopher Tate84725812010-02-04 15:52:40 -08005596 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005597 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5598 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005599
Chris Tate44ab8452010-11-16 15:10:49 -08005600 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005601 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005602
Christopher Tate73a3cb32010-12-13 18:27:26 -08005603 if (mEnded) {
5604 throw new IllegalStateException("Restore session already ended");
5605 }
5606
Dan Egnor0084da52009-07-29 12:57:16 -07005607 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005608 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5609 return -1;
5610 }
5611
5612 if (mPackageName != null) {
5613 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005614 return -1;
5615 }
5616
Christopher Tate21ab6a52009-09-24 18:01:46 -07005617 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005618 for (int i = 0; i < mRestoreSets.length; i++) {
5619 if (token == mRestoreSets[i].token) {
5620 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005621 mWakelock.acquire();
5622 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005623 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005624 mBackupHandler.sendMessage(msg);
5625 Binder.restoreCallingIdentity(oldId);
5626 return 0;
5627 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005628 }
5629 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005630
Joe Onorato8a9b2202010-02-26 18:56:32 -08005631 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005632 return -1;
5633 }
5634
Christopher Tate284f1bb2011-07-07 14:31:18 -07005635 public synchronized int restoreSome(long token, IRestoreObserver observer,
5636 String[] packages) {
5637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5638 "performRestore");
5639
5640 if (DEBUG) {
5641 StringBuilder b = new StringBuilder(128);
5642 b.append("restoreSome token=");
5643 b.append(Long.toHexString(token));
5644 b.append(" observer=");
5645 b.append(observer.toString());
5646 b.append(" packages=");
5647 if (packages == null) {
5648 b.append("null");
5649 } else {
5650 b.append('{');
5651 boolean first = true;
5652 for (String s : packages) {
5653 if (!first) {
5654 b.append(", ");
5655 } else first = false;
5656 b.append(s);
5657 }
5658 b.append('}');
5659 }
5660 Slog.d(TAG, b.toString());
5661 }
5662
5663 if (mEnded) {
5664 throw new IllegalStateException("Restore session already ended");
5665 }
5666
5667 if (mRestoreTransport == null || mRestoreSets == null) {
5668 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5669 return -1;
5670 }
5671
5672 if (mPackageName != null) {
5673 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5674 return -1;
5675 }
5676
5677 synchronized (mQueueLock) {
5678 for (int i = 0; i < mRestoreSets.length; i++) {
5679 if (token == mRestoreSets[i].token) {
5680 long oldId = Binder.clearCallingIdentity();
5681 mWakelock.acquire();
5682 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5683 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5684 packages, true);
5685 mBackupHandler.sendMessage(msg);
5686 Binder.restoreCallingIdentity(oldId);
5687 return 0;
5688 }
5689 }
5690 }
5691
5692 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5693 return -1;
5694 }
5695
Christopher Tate84725812010-02-04 15:52:40 -08005696 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005697 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005698
Christopher Tate73a3cb32010-12-13 18:27:26 -08005699 if (mEnded) {
5700 throw new IllegalStateException("Restore session already ended");
5701 }
5702
Chris Tate44ab8452010-11-16 15:10:49 -08005703 if (mPackageName != null) {
5704 if (! mPackageName.equals(packageName)) {
5705 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5706 + " on session for package " + mPackageName);
5707 return -1;
5708 }
5709 }
5710
Christopher Tate84725812010-02-04 15:52:40 -08005711 PackageInfo app = null;
5712 try {
5713 app = mPackageManager.getPackageInfo(packageName, 0);
5714 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005715 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005716 return -1;
5717 }
5718
5719 // If the caller is not privileged and is not coming from the target
5720 // app's uid, throw a permission exception back to the caller.
5721 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5722 Binder.getCallingPid(), Binder.getCallingUid());
5723 if ((perm == PackageManager.PERMISSION_DENIED) &&
5724 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005725 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005726 + " or calling uid=" + Binder.getCallingUid());
5727 throw new SecurityException("No permission to restore other packages");
5728 }
5729
Christopher Tate7d411a32010-02-26 11:27:08 -08005730 // If the package has no backup agent, we obviously cannot proceed
5731 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005732 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005733 return -1;
5734 }
5735
Christopher Tate84725812010-02-04 15:52:40 -08005736 // So far so good; we're allowed to try to restore this package. Now
5737 // check whether there is data for it in the current dataset, falling back
5738 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005739 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005740
5741 // If we didn't come up with a place to look -- no ancestral dataset and
5742 // the app has never been backed up from this device -- there's nothing
5743 // to do but return failure.
5744 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005745 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005746 return -1;
5747 }
5748
5749 // Ready to go: enqueue the restore request and claim success
5750 long oldId = Binder.clearCallingIdentity();
5751 mWakelock.acquire();
5752 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005753 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005754 mBackupHandler.sendMessage(msg);
5755 Binder.restoreCallingIdentity(oldId);
5756 return 0;
5757 }
5758
Christopher Tate73a3cb32010-12-13 18:27:26 -08005759 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5760 class EndRestoreRunnable implements Runnable {
5761 BackupManagerService mBackupManager;
5762 ActiveRestoreSession mSession;
5763
5764 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5765 mBackupManager = manager;
5766 mSession = session;
5767 }
5768
5769 public void run() {
5770 // clean up the session's bookkeeping
5771 synchronized (mSession) {
5772 try {
5773 if (mSession.mRestoreTransport != null) {
5774 mSession.mRestoreTransport.finishRestore();
5775 }
5776 } catch (Exception e) {
5777 Slog.e(TAG, "Error in finishRestore", e);
5778 } finally {
5779 mSession.mRestoreTransport = null;
5780 mSession.mEnded = true;
5781 }
5782 }
5783
5784 // clean up the BackupManagerService side of the bookkeeping
5785 // and cancel any pending timeout message
5786 mBackupManager.clearRestoreSession(mSession);
5787 }
5788 }
5789
Dan Egnor0084da52009-07-29 12:57:16 -07005790 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005791 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005792
Christopher Tate73a3cb32010-12-13 18:27:26 -08005793 if (mEnded) {
5794 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005795 }
5796
Christopher Tate73a3cb32010-12-13 18:27:26 -08005797 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005798 }
5799 }
5800
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005801 @Override
5802 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5804
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005805 long identityToken = Binder.clearCallingIdentity();
5806 try {
5807 dumpInternal(pw);
5808 } finally {
5809 Binder.restoreCallingIdentity(identityToken);
5810 }
5811 }
5812
5813 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005814 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005815 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005816 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005817 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005818 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005819 if (mBackupRunning) pw.println("Backup currently running");
5820 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005821 + " (now = " + System.currentTimeMillis() + ')');
5822 pw.println(" next scheduled: " + mNextBackupPass);
5823
Christopher Tate91717492009-06-26 21:07:13 -07005824 pw.println("Available transports:");
5825 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005826 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5827 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005828 IBackupTransport transport = getTransport(t);
5829 File dir = new File(mBaseStateDir, transport.transportDirName());
5830 pw.println(" destination: " + transport.currentDestinationString());
5831 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005832 for (File f : dir.listFiles()) {
5833 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5834 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005835 } catch (Exception e) {
5836 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005837 pw.println(" Error: " + e);
5838 }
Christopher Tate91717492009-06-26 21:07:13 -07005839 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005840
5841 pw.println("Pending init: " + mPendingInits.size());
5842 for (String s : mPendingInits) {
5843 pw.println(" " + s);
5844 }
5845
Christopher Tate6de74ff2012-01-17 15:20:32 -08005846 if (DEBUG_BACKUP_TRACE) {
5847 synchronized (mBackupTrace) {
5848 if (!mBackupTrace.isEmpty()) {
5849 pw.println("Most recent backup trace:");
5850 for (String s : mBackupTrace) {
5851 pw.println(" " + s);
5852 }
5853 }
5854 }
5855 }
5856
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005857 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005858 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005859 for (int i=0; i<N; i++) {
5860 int uid = mBackupParticipants.keyAt(i);
5861 pw.print(" uid: ");
5862 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005863 HashSet<String> participants = mBackupParticipants.valueAt(i);
5864 for (String app: participants) {
5865 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005866 }
5867 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005868
Christopher Tateb49ceb32010-02-08 16:22:24 -08005869 pw.println("Ancestral packages: "
5870 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005871 if (mAncestralPackages != null) {
5872 for (String pkg : mAncestralPackages) {
5873 pw.println(" " + pkg);
5874 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005875 }
5876
Christopher Tate73e02522009-07-15 14:18:26 -07005877 pw.println("Ever backed up: " + mEverStoredApps.size());
5878 for (String pkg : mEverStoredApps) {
5879 pw.println(" " + pkg);
5880 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005881
5882 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005883 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005884 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005885 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005886 }
5887 }
Christopher Tate487529a2009-04-29 14:03:25 -07005888}