blob: 5e2b42551d95a4f0adffe2033419950cebcaebed [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;
Christopher Tate97ea1222012-05-17 14:59:41 -0700732 mProvisioned = Settings.Secure.getInt(resolver,
733 Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
734 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(
739 Settings.Secure.getUriFor(Settings.Secure.DEVICE_PROVISIONED),
740 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 Tate3799bc22009-05-06 16:13:56 -07001477 }
1478 }
1479
Christopher Tate181fafa2009-05-14 11:12:14 -07001480 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001481 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001482 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001483 int flags = PackageManager.GET_SIGNATURES;
1484 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1485 int N = packages.size();
1486 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001487 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001488 try {
1489 ApplicationInfo app = pkg.applicationInfo;
1490 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001491 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001492 packages.remove(a);
1493 }
1494 else {
1495 // we will need the shared library path, so look that up and store it here
1496 app = mPackageManager.getApplicationInfo(pkg.packageName,
1497 PackageManager.GET_SHARED_LIBRARY_FILES);
1498 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1499 }
1500 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001501 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001502 }
1503 }
Dan Egnorefe52642009-06-24 00:16:33 -07001504 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001505 }
Christopher Tateaa088442009-06-16 18:25:46 -07001506
Christopher Tate84725812010-02-04 15:52:40 -08001507 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001508 // backed up at least once
1509 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001510 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1511
1512 synchronized (mEverStoredApps) {
1513 if (!mEverStoredApps.add(packageName)) return;
1514
1515 RandomAccessFile out = null;
1516 try {
1517 out = new RandomAccessFile(mEverStored, "rws");
1518 out.seek(out.length());
1519 out.writeUTF(packageName);
1520 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001522 } finally {
1523 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001524 }
1525 }
1526 }
1527
Christopher Tatee97e8072009-07-15 16:45:50 -07001528 // Remove our awareness of having ever backed up the given package
1529 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001530 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1531 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001532
Dan Egnor852f8e42009-09-30 11:20:45 -07001533 synchronized (mEverStoredApps) {
1534 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1535 // we'll recognize on initialization time that the package no longer
1536 // exists and fix it up then.
1537 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1538 RandomAccessFile known = null;
1539 try {
1540 known = new RandomAccessFile(tempKnownFile, "rws");
1541 mEverStoredApps.remove(packageName);
1542 for (String s : mEverStoredApps) {
1543 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001544 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001545 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001546 known.close();
1547 known = null;
1548 if (!tempKnownFile.renameTo(mEverStored)) {
1549 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1550 }
1551 } catch (IOException e) {
1552 // Bad: we couldn't create the new copy. For safety's sake we
1553 // abandon the whole process and remove all what's-backed-up
1554 // state entirely, meaning we'll force a backup pass for every
1555 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001557 mEverStoredApps.clear();
1558 tempKnownFile.delete();
1559 mEverStored.delete();
1560 } finally {
1561 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001562 }
1563 }
1564 }
1565
Christopher Tateb49ceb32010-02-08 16:22:24 -08001566 // Persistently record the current and ancestral backup tokens as well
1567 // as the set of packages with data [supposedly] available in the
1568 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001569 void writeRestoreTokens() {
1570 try {
1571 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001572
1573 // First, the version number of this record, for futureproofing
1574 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1575
1576 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001577 af.writeLong(mAncestralToken);
1578 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001579
1580 // Now write the set of ancestral packages
1581 if (mAncestralPackages == null) {
1582 af.writeInt(-1);
1583 } else {
1584 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001586 for (String pkgName : mAncestralPackages) {
1587 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001588 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001589 }
1590 }
Christopher Tate84725812010-02-04 15:52:40 -08001591 af.close();
1592 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001593 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001594 }
1595 }
1596
Dan Egnor87a02bc2009-06-17 02:30:10 -07001597 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001598 private IBackupTransport getTransport(String transportName) {
1599 synchronized (mTransports) {
1600 IBackupTransport transport = mTransports.get(transportName);
1601 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001602 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001603 }
1604 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001605 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001606 }
1607
Christopher Tatedf01dea2009-06-09 20:45:02 -07001608 // fire off a backup agent, blocking until it attaches or times out
1609 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1610 IBackupAgent agent = null;
1611 synchronized(mAgentConnectLock) {
1612 mConnecting = true;
1613 mConnectedAgent = null;
1614 try {
1615 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001617
1618 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001619 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001620 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1621 while (mConnecting && mConnectedAgent == null
1622 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001623 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001624 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001625 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001626 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001627 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628 return null;
1629 }
1630 }
1631
1632 // if we timed out with no connect, abort and move on
1633 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001635 return null;
1636 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001637 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 agent = mConnectedAgent;
1639 }
1640 } catch (RemoteException e) {
1641 // can't happen
1642 }
1643 }
1644 return agent;
1645 }
1646
Christopher Tatec7b31e32009-06-10 15:49:30 -07001647 // clear an application's data, blocking until the operation completes or times out
1648 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001649 // Don't wipe packages marked allowClearUserData=false
1650 try {
1651 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1652 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001653 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001654 + packageName);
1655 return;
1656 }
1657 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001658 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001659 return;
1660 }
1661
Christopher Tatec7b31e32009-06-10 15:49:30 -07001662 ClearDataObserver observer = new ClearDataObserver();
1663
1664 synchronized(mClearDataLock) {
1665 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001666 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001667 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001668 } catch (RemoteException e) {
1669 // can't happen because the activity manager is in this process
1670 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001671
1672 // only wait 10 seconds for the clear data to happen
1673 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1674 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1675 try {
1676 mClearDataLock.wait(5000);
1677 } catch (InterruptedException e) {
1678 // won't happen, but still.
1679 mClearingData = false;
1680 }
1681 }
1682 }
1683 }
1684
1685 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001686 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001687 synchronized(mClearDataLock) {
1688 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001689 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001690 }
1691 }
1692 }
1693
Christopher Tate1bb69062010-02-19 17:02:12 -08001694 // Get the restore-set token for the best-available restore set for this package:
1695 // the active set if possible, else the ancestral one. Returns zero if none available.
1696 long getAvailableRestoreToken(String packageName) {
1697 long token = mAncestralToken;
1698 synchronized (mQueueLock) {
1699 if (mEverStoredApps.contains(packageName)) {
1700 token = mCurrentToken;
1701 }
1702 }
1703 return token;
1704 }
1705
Christopher Tate44a27902010-01-27 17:15:49 -08001706 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001707 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1708
1709 interface BackupRestoreTask {
1710 // Execute one tick of whatever state machine the task implements
1711 void execute();
1712
1713 // An operation that wanted a callback has completed
1714 void operationComplete();
1715
1716 // An operation that wanted a callback has timed out
1717 void handleTimeout();
1718 }
1719
1720 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1721 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1722 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001723 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001724 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1725
1726 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1727 mBackupHandler.sendMessageDelayed(msg, interval);
1728 }
1729 }
1730
1731 // synchronous waiter case
1732 boolean waitUntilOperationComplete(int token) {
1733 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1734 + Integer.toHexString(token));
1735 int finalState = OP_PENDING;
1736 Operation op = null;
1737 synchronized (mCurrentOpLock) {
1738 while (true) {
1739 op = mCurrentOperations.get(token);
1740 if (op == null) {
1741 // mysterious disappearance: treat as success with no callback
1742 break;
1743 } else {
1744 if (op.state == OP_PENDING) {
1745 try {
1746 mCurrentOpLock.wait();
1747 } catch (InterruptedException e) {}
1748 // When the wait is notified we loop around and recheck the current state
1749 } else {
1750 // No longer pending; we're done
1751 finalState = op.state;
1752 break;
1753 }
Christopher Tate44a27902010-01-27 17:15:49 -08001754 }
Christopher Tate44a27902010-01-27 17:15:49 -08001755 }
1756 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001757
Christopher Tate44a27902010-01-27 17:15:49 -08001758 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001759 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001760 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001761 return finalState == OP_ACKNOWLEDGED;
1762 }
1763
Christopher Tate8e294d42011-08-31 20:37:12 -07001764 void handleTimeout(int token, Object obj) {
1765 // Notify any synchronous waiters
1766 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001767 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001768 op = mCurrentOperations.get(token);
1769 if (MORE_DEBUG) {
1770 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1771 + " but no op found");
1772 }
1773 int state = (op != null) ? op.state : OP_TIMEOUT;
1774 if (state == OP_PENDING) {
1775 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1776 op.state = OP_TIMEOUT;
1777 mCurrentOperations.put(token, op);
1778 }
1779 mCurrentOpLock.notifyAll();
1780 }
1781
1782 // If there's a TimeoutHandler for this event, call it
1783 if (op != null && op.callback != null) {
1784 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001785 }
Christopher Tate44a27902010-01-27 17:15:49 -08001786 }
1787
Christopher Tate043dadc2009-06-02 16:11:00 -07001788 // ----- Back up a set of applications via a worker thread -----
1789
Christopher Tate8e294d42011-08-31 20:37:12 -07001790 enum BackupState {
1791 INITIAL,
1792 RUNNING_QUEUE,
1793 FINAL
1794 }
1795
1796 class PerformBackupTask implements BackupRestoreTask {
1797 private static final String TAG = "PerformBackupTask";
1798
Christopher Tateaa088442009-06-16 18:25:46 -07001799 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001800 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001801 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001802 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001803 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001804 BackupState mCurrentState;
1805
1806 // carried information about the current in-flight operation
1807 PackageInfo mCurrentPackage;
1808 File mSavedStateName;
1809 File mBackupDataName;
1810 File mNewStateName;
1811 ParcelFileDescriptor mSavedState;
1812 ParcelFileDescriptor mBackupData;
1813 ParcelFileDescriptor mNewState;
1814 int mStatus;
1815 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001816
Christopher Tate44a27902010-01-27 17:15:49 -08001817 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001818 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001819 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001820 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001821 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001822
1823 try {
1824 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1825 } catch (RemoteException e) {
1826 // can't happen; the transport is local
1827 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001828
1829 mCurrentState = BackupState.INITIAL;
1830 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001831
1832 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001833 }
1834
Christopher Tate8e294d42011-08-31 20:37:12 -07001835 // Main entry point: perform one chunk of work, updating the state as appropriate
1836 // and reposting the next chunk to the primary backup handler thread.
1837 @Override
1838 public void execute() {
1839 switch (mCurrentState) {
1840 case INITIAL:
1841 beginBackup();
1842 break;
1843
1844 case RUNNING_QUEUE:
1845 invokeNextAgent();
1846 break;
1847
1848 case FINAL:
1849 if (!mFinished) finalizeBackup();
1850 else {
1851 Slog.e(TAG, "Duplicate finish");
1852 }
Christopher Tate2982d062011-09-06 20:35:24 -07001853 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001854 break;
1855 }
1856 }
1857
1858 // We're starting a backup pass. Initialize the transport and send
1859 // the PM metadata blob if we haven't already.
1860 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001861 if (DEBUG_BACKUP_TRACE) {
1862 clearBackupTrace();
1863 StringBuilder b = new StringBuilder(256);
1864 b.append("beginBackup: [");
1865 for (BackupRequest req : mOriginalQueue) {
1866 b.append(' ');
1867 b.append(req.packageName);
1868 }
1869 b.append(" ]");
1870 addBackupTrace(b.toString());
1871 }
1872
Christopher Tate8e294d42011-08-31 20:37:12 -07001873 mStatus = BackupConstants.TRANSPORT_OK;
1874
1875 // Sanity check: if the queue is empty we have no work to do.
1876 if (mOriginalQueue.isEmpty()) {
1877 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001878 addBackupTrace("queue empty at begin");
1879 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001880 return;
1881 }
1882
1883 // We need to retain the original queue contents in case of transport
1884 // failure, but we want a working copy that we can manipulate along
1885 // the way.
1886 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1887
Joe Onorato8a9b2202010-02-26 18:56:32 -08001888 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001889
Christopher Tate8e294d42011-08-31 20:37:12 -07001890 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001891 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001892 final String transportName = mTransport.transportDirName();
1893 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001894
Dan Egnor852f8e42009-09-30 11:20:45 -07001895 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001896 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001897 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001898 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001899 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001900 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001901
1902 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001904 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001905 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001907 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001908 }
Dan Egnor01445162009-09-21 17:04:05 -07001909 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001910
1911 // The package manager doesn't have a proper <application> etc, but since
1912 // it's running here in the system process we can just set up its agent
1913 // directly and use a synthetic BackupRequest. We always run this pass
1914 // because it's cheap and this way we guarantee that we don't get out of
1915 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001916 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001917 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1918 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001919 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001920 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001921 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001922 }
Christopher Tate90967f42009-09-20 15:28:33 -07001923
Christopher Tate8e294d42011-08-31 20:37:12 -07001924 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1925 // The backend reports that our dataset has been wiped. Note this in
1926 // the event log; the no-success code below will reset the backup
1927 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001928 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001929 }
1930 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001931 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001932 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001933 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001934 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001935 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1936 // metadata and its completion/timeout callback will continue the state
1937 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001938 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001939 if (mStatus != BackupConstants.TRANSPORT_OK) {
1940 // if things went wrong at this point, we need to
1941 // restage everything and try again later.
1942 resetBackupState(mStateDir); // Just to make sure.
1943 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001944 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001945 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001946 }
1947
Christopher Tate8e294d42011-08-31 20:37:12 -07001948 // Transport has been initialized and the PM metadata submitted successfully
1949 // if that was warranted. Now we process the single next thing in the queue.
1950 void invokeNextAgent() {
1951 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001952 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001953
Christopher Tate8e294d42011-08-31 20:37:12 -07001954 // Sanity check that we have work to do. If not, skip to the end where
1955 // we reestablish the wakelock invariants etc.
1956 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001957 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001958 executeNextState(BackupState.FINAL);
1959 return;
1960 }
1961
1962 // pop the entry we're going to process on this step
1963 BackupRequest request = mQueue.get(0);
1964 mQueue.remove(0);
1965
1966 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001967 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001968
1969 // Verify that the requested app exists; it might be something that
1970 // requested a backup but was then uninstalled. The request was
1971 // journalled and rather than tamper with the journal it's safer
1972 // to sanity-check here. This also gives us the classname of the
1973 // package's backup agent.
1974 try {
1975 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1976 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001977 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1978 // The manifest has changed but we had a stale backup request pending.
1979 // This won't happen again because the app won't be requesting further
1980 // backups.
1981 Slog.i(TAG, "Package " + request.packageName
1982 + " no longer supports backup; skipping");
1983 addBackupTrace("skipping - no agent, completion is noop");
1984 executeNextState(BackupState.RUNNING_QUEUE);
1985 return;
1986 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001987
Christopher Tate043dadc2009-06-02 16:11:00 -07001988 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001989 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001990 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1991 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001992 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001993 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001994 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001995 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1996 // at this point we'll either get a completion callback from the
1997 // agent, or a timeout message on the main handler. either way, we're
1998 // done here as long as we're successful so far.
1999 } else {
2000 // Timeout waiting for the agent
2001 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002002 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002003 } catch (SecurityException ex) {
2004 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002005 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002006 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002007 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002008 }
2009 } catch (NameNotFoundException e) {
2010 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002011 addBackupTrace("no such package");
2012 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002013 } finally {
2014 mWakelock.setWorkSource(null);
2015
2016 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002017 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002018 if (mStatus != BackupConstants.TRANSPORT_OK) {
2019 BackupState nextState = BackupState.RUNNING_QUEUE;
2020
2021 // An agent-level failure means we reenqueue this one agent for
2022 // a later retry, but otherwise proceed normally.
2023 if (mStatus == BackupConstants.AGENT_ERROR) {
2024 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2025 + " - restaging");
2026 dataChangedImpl(request.packageName);
2027 mStatus = BackupConstants.TRANSPORT_OK;
2028 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002029 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2030 // Failed lookup of the app, so we couldn't bring up an agent, but
2031 // we're otherwise fine. Just drop it and go on to the next as usual.
2032 mStatus = BackupConstants.TRANSPORT_OK;
2033 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 // Transport-level failure means we reenqueue everything
2035 revertAndEndBackup();
2036 nextState = BackupState.FINAL;
2037 }
2038
2039 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002040 } else {
2041 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002042 }
2043 }
2044 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002045
Christopher Tate8e294d42011-08-31 20:37:12 -07002046 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002047 addBackupTrace("finishing");
2048
Christopher Tate8e294d42011-08-31 20:37:12 -07002049 // Either backup was successful, in which case we of course do not need
2050 // this pass's journal any more; or it failed, in which case we just
2051 // re-enqueued all of these packages in the current active journal.
2052 // Either way, we no longer need this pass's journal.
2053 if (mJournal != null && !mJournal.delete()) {
2054 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2055 }
2056
2057 // If everything actually went through and this is the first time we've
2058 // done a backup, we can now record what the current backup dataset token
2059 // is.
2060 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002061 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002062 try {
2063 mCurrentToken = mTransport.getCurrentRestoreSet();
2064 } catch (RemoteException e) {} // can't happen
2065 writeRestoreTokens();
2066 }
2067
Christopher Tate336a6492011-10-05 16:05:43 -07002068 // Set up the next backup pass - at this point we can set mBackupRunning
2069 // to false to allow another pass to fire, because we're done with the
2070 // state machine sequence and the wakelock is refcounted.
2071 synchronized (mQueueLock) {
2072 mBackupRunning = false;
2073 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002074 // Make sure we back up everything and perform the one-time init
2075 clearMetadata();
2076 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002077 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002078 backupNow();
2079 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002080 }
2081
2082 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002083 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002084 Slog.i(TAG, "Backup pass finished.");
2085 mWakelock.release();
2086 }
2087
Christopher Tatee659fb92011-10-10 16:34:50 -07002088 // Remove the PM metadata state. This will generate an init on the next pass.
2089 void clearMetadata() {
2090 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2091 if (pmState.exists()) pmState.delete();
2092 }
2093
Christopher Tate8e294d42011-08-31 20:37:12 -07002094 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2095 // handler in case it doesn't get back to us.
2096 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002097 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002098 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2099 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002100
Christopher Tate8e294d42011-08-31 20:37:12 -07002101 mSavedStateName = new File(mStateDir, packageName);
2102 mBackupDataName = new File(mDataDir, packageName + ".data");
2103 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002104
Christopher Tate8e294d42011-08-31 20:37:12 -07002105 mSavedState = null;
2106 mBackupData = null;
2107 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002108
Christopher Tate4a627c72011-04-01 14:43:32 -07002109 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002110 try {
2111 // Look up the package info & signatures. This is first so that if it
2112 // throws an exception, there's no file setup yet that would need to
2113 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002114 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002115 // The metadata 'package' is synthetic; construct one and make
2116 // sure our global state is pointed at it
2117 mCurrentPackage = new PackageInfo();
2118 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002119 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002120
Christopher Tatec7b31e32009-06-10 15:49:30 -07002121 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002122 // the saved-state "file". This is by definition an incremental,
2123 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002124 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002125 ParcelFileDescriptor.MODE_READ_ONLY |
2126 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127
Christopher Tate8e294d42011-08-31 20:37:12 -07002128 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002129 ParcelFileDescriptor.MODE_READ_WRITE |
2130 ParcelFileDescriptor.MODE_CREATE |
2131 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002132
Christopher Tate8e294d42011-08-31 20:37:12 -07002133 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002134 ParcelFileDescriptor.MODE_READ_WRITE |
2135 ParcelFileDescriptor.MODE_CREATE |
2136 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002137
Christopher Tate44a27902010-01-27 17:15:49 -08002138 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002139 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002140 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002141 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002142 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002143 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002145 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002146 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2147 e.toString());
2148 agentErrorCleanup();
2149 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002150 }
2151
Christopher Tate8e294d42011-08-31 20:37:12 -07002152 // At this point the agent is off and running. The next thing to happen will
2153 // either be a callback from the agent, at which point we'll process its data
2154 // for transport, or a timeout. Either way the next phase will happen in
2155 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002156 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002157 return BackupConstants.TRANSPORT_OK;
2158 }
2159
2160 @Override
2161 public void operationComplete() {
2162 // Okay, the agent successfully reported back to us. Spin the data off to the
2163 // transport and proceed with the next stage.
2164 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2165 + mCurrentPackage.packageName);
2166 mBackupHandler.removeMessages(MSG_TIMEOUT);
2167 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002168 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002169
2170 ParcelFileDescriptor backupData = null;
2171 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002172 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002173 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002174 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002175 if (mStatus == BackupConstants.TRANSPORT_OK) {
2176 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002177 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002178 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002179 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002180 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002181
Dan Egnor83861e72009-09-17 16:17:55 -07002182 // TODO - We call finishBackup() for each application backed up, because
2183 // we need to know now whether it succeeded or failed. Instead, we should
2184 // hold off on finishBackup() until the end, which implies holding off on
2185 // renaming *all* the output state files (see below) until that happens.
2186
Christopher Tate6de74ff2012-01-17 15:20:32 -08002187 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002188 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002191 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002192 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002193 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002195 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002196 }
2197
2198 // After successful transport, delete the now-stale data
2199 // and juggle the files so that next time we supply the agent
2200 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002201 if (mStatus == BackupConstants.TRANSPORT_OK) {
2202 mBackupDataName.delete();
2203 mNewStateName.renameTo(mSavedStateName);
2204 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2205 mCurrentPackage.packageName, size);
2206 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002207 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002208 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2209 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002210 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002211 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002212 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2213 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2214 mCurrentPackage.packageName);
2215 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002216 } finally {
2217 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002218 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002219
Christopher Tate8e294d42011-08-31 20:37:12 -07002220 // If we encountered an error here it's a transport-level failure. That
2221 // means we need to halt everything and reschedule everything for next time.
2222 final BackupState nextState;
2223 if (mStatus != BackupConstants.TRANSPORT_OK) {
2224 revertAndEndBackup();
2225 nextState = BackupState.FINAL;
2226 } else {
2227 // Success! Proceed with the next app if any, otherwise we're done.
2228 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2229 }
2230
2231 executeNextState(nextState);
2232 }
2233
2234 @Override
2235 public void handleTimeout() {
2236 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2237 // it for the next time we run a backup pass.
2238 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2239 // fail repeatedly (i.e. have proved themselves to be buggy).
2240 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2241 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2242 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002243 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002244 agentErrorCleanup();
2245 dataChangedImpl(mCurrentPackage.packageName);
2246 }
2247
2248 void revertAndEndBackup() {
2249 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002250 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002251 for (BackupRequest request : mOriginalQueue) {
2252 dataChangedImpl(request.packageName);
2253 }
2254 // We also want to reset the backup schedule based on whatever
2255 // the transport suggests by way of retry/backoff time.
2256 restartBackupAlarm();
2257 }
2258
2259 void agentErrorCleanup() {
2260 mBackupDataName.delete();
2261 mNewStateName.delete();
2262 clearAgentState();
2263
2264 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2265 }
2266
2267 // Cleanup common to both success and failure cases
2268 void clearAgentState() {
2269 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2270 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2271 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2272 mSavedState = mBackupData = mNewState = null;
2273 synchronized (mCurrentOpLock) {
2274 mCurrentOperations.clear();
2275 }
2276
2277 // If this was a pseudopackage there's no associated Activity Manager state
2278 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002279 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002280 try { // unbind even on timeout, just in case
2281 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2282 } catch (RemoteException e) {}
2283 }
2284 }
2285
2286 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002287 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002288 synchronized (mQueueLock) {
2289 try {
2290 startBackupAlarmsLocked(mTransport.requestBackupTime());
2291 } catch (RemoteException e) { /* cannot happen */ }
2292 }
2293 }
2294
2295 void executeNextState(BackupState nextState) {
2296 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2297 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002298 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002299 mCurrentState = nextState;
2300 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2301 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002302 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002303 }
2304
Christopher Tatedf01dea2009-06-09 20:45:02 -07002305
Christopher Tate4a627c72011-04-01 14:43:32 -07002306 // ----- Full backup to a file/socket -----
2307
2308 class PerformFullBackupTask implements Runnable {
2309 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002310 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002311 IFullBackupRestoreObserver mObserver;
2312 boolean mIncludeApks;
2313 boolean mIncludeShared;
2314 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002315 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002316 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002317 String mCurrentPassword;
2318 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002319 AtomicBoolean mLatchObject;
2320 File mFilesDir;
2321 File mManifestFile;
2322
Christopher Tate7926a692011-07-11 11:31:57 -07002323 class FullBackupRunner implements Runnable {
2324 PackageInfo mPackage;
2325 IBackupAgent mAgent;
2326 ParcelFileDescriptor mPipe;
2327 int mToken;
2328 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002329 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002330
2331 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002332 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002333 mPackage = pack;
2334 mAgent = agent;
2335 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2336 mToken = token;
2337 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002338 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002339 }
2340
2341 @Override
2342 public void run() {
2343 try {
2344 BackupDataOutput output = new BackupDataOutput(
2345 mPipe.getFileDescriptor());
2346
Christopher Tate73d73692012-01-20 17:11:31 -08002347 if (mWriteManifest) {
2348 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2349 writeAppManifest(mPackage, mManifestFile, mSendApk);
2350 FullBackup.backupToTar(mPackage.packageName, null, null,
2351 mFilesDir.getAbsolutePath(),
2352 mManifestFile.getAbsolutePath(),
2353 output);
2354 }
Christopher Tate7926a692011-07-11 11:31:57 -07002355
2356 if (mSendApk) {
2357 writeApkToBackup(mPackage, output);
2358 }
2359
Christopher Tatec58efa62011-08-01 19:20:14 -07002360 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002361 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002362 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2363 } catch (IOException e) {
2364 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2365 } catch (RemoteException e) {
2366 Slog.e(TAG, "Remote agent vanished during full backup of "
2367 + mPackage.packageName);
2368 } finally {
2369 try {
2370 mPipe.close();
2371 } catch (IOException e) {}
2372 }
2373 }
2374 }
2375
Christopher Tate4a627c72011-04-01 14:43:32 -07002376 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002377 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002378 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002379 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002380 mOutputFile = fd;
2381 mObserver = observer;
2382 mIncludeApks = includeApks;
2383 mIncludeShared = includeShared;
2384 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002385 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002386 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002387 mCurrentPassword = curPassword;
2388 // when backing up, if there is a current backup password, we require that
2389 // the user use a nonempty encryption password as well. if one is supplied
2390 // in the UI we use that, but if the UI was left empty we fall back to the
2391 // current backup password (which was supplied by the user as well).
2392 if (encryptPassword == null || "".equals(encryptPassword)) {
2393 mEncryptPassword = curPassword;
2394 } else {
2395 mEncryptPassword = encryptPassword;
2396 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002397 mLatchObject = latch;
2398
2399 mFilesDir = new File("/data/system");
2400 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2401 }
2402
2403 @Override
2404 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002405 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002406
Christopher Tateb0628bf2011-06-02 15:08:13 -07002407 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002408 sendStartBackup();
2409
2410 // doAllApps supersedes the package set if any
2411 if (mAllApps) {
2412 packagesToBackup = mPackageManager.getInstalledPackages(
2413 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002414 // Exclude system apps if we've been asked to do so
2415 if (mIncludeSystem == false) {
2416 for (int i = 0; i < packagesToBackup.size(); ) {
2417 PackageInfo pkg = packagesToBackup.get(i);
2418 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2419 packagesToBackup.remove(i);
2420 } else {
2421 i++;
2422 }
2423 }
2424 }
2425 }
2426
2427 // Now process the command line argument packages, if any. Note that explicitly-
2428 // named system-partition packages will be included even if includeSystem was
2429 // set to false.
2430 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002431 for (String pkgName : mPackages) {
2432 try {
2433 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2434 PackageManager.GET_SIGNATURES));
2435 } catch (NameNotFoundException e) {
2436 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2437 }
2438 }
2439 }
2440
Christopher Tate73d73692012-01-20 17:11:31 -08002441 // Cull any packages that have indicated that backups are not permitted, as well
2442 // as any explicit mention of the 'special' shared-storage agent package (we
2443 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002444 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002445 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002446 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2447 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002448 packagesToBackup.remove(i);
2449 } else {
2450 i++;
2451 }
2452 }
2453
Christopher Tate7926a692011-07-11 11:31:57 -07002454 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002455 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002456
Christopher Tate4a627c72011-04-01 14:43:32 -07002457 PackageInfo pkg = null;
2458 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002459 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002460 boolean compressing = COMPRESS_FULL_BACKUPS;
2461 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002462
Christopher Tateeef4ae42011-08-05 13:15:53 -07002463 // Verify that the given password matches the currently-active
2464 // backup password, if any
2465 if (hasBackupPassword()) {
2466 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2467 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2468 return;
2469 }
2470 }
2471
Christopher Tate7bdb0962011-07-13 19:30:21 -07002472 // Write the global file header. All strings are UTF-8 encoded; lines end
2473 // with a '\n' byte. Actual backup data begins immediately following the
2474 // final '\n'.
2475 //
2476 // line 1: "ANDROID BACKUP"
2477 // line 2: backup file format version, currently "1"
2478 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002479 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2480 //
2481 // When line 4 is not "none", then additional header data follows:
2482 //
2483 // line 5: user password salt [hex]
2484 // line 6: master key checksum salt [hex]
2485 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2486 // line 8: IV of the user key [hex]
2487 // line 9: master key blob [hex]
2488 // IV of the master key, master key itself, master key checksum hash
2489 //
2490 // The master key checksum is the master key plus its checksum salt, run through
2491 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2492 // correct password for decrypting the archive: the master key decrypted from
2493 // the archive using the user-supplied password is also run through PBKDF2 in
2494 // this way, and if the result does not match the checksum as stored in the
2495 // archive, then we know that the user-supplied password does not match the
2496 // archive's.
2497 StringBuilder headerbuf = new StringBuilder(1024);
2498
Christopher Tate7bdb0962011-07-13 19:30:21 -07002499 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002500 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2501 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002502
2503 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002504 // Set up the encryption stage if appropriate, and emit the correct header
2505 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002506 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2507 } else {
2508 headerbuf.append("none\n");
2509 }
2510
Christopher Tate7bdb0962011-07-13 19:30:21 -07002511 byte[] header = headerbuf.toString().getBytes("UTF-8");
2512 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002513
2514 // Set up the compression stage feeding into the encryption stage (if any)
2515 if (compressing) {
2516 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2517 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2518 }
2519
2520 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002521 } catch (Exception e) {
2522 // Should never happen!
2523 Slog.e(TAG, "Unable to emit archive header", e);
2524 return;
2525 }
2526
Christopher Tate73d73692012-01-20 17:11:31 -08002527 // Shared storage if requested
2528 if (mIncludeShared) {
2529 try {
2530 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2531 packagesToBackup.add(pkg);
2532 } catch (NameNotFoundException e) {
2533 Slog.e(TAG, "Unable to find shared-storage backup handler");
2534 }
2535 }
2536
Christopher Tateb0628bf2011-06-02 15:08:13 -07002537 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002538 int N = packagesToBackup.size();
2539 for (int i = 0; i < N; i++) {
2540 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002541 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002542 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002543
Christopher Tate6853fcf2011-08-10 17:52:21 -07002544 // Done!
2545 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002546 } catch (RemoteException e) {
2547 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002548 } catch (Exception e) {
2549 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002550 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002551 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002552 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002553 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002554 mOutputFile.close();
2555 } catch (IOException e) {
2556 /* nothing we can do about this */
2557 }
2558 synchronized (mCurrentOpLock) {
2559 mCurrentOperations.clear();
2560 }
2561 synchronized (mLatchObject) {
2562 mLatchObject.set(true);
2563 mLatchObject.notifyAll();
2564 }
2565 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002566 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002567 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002568 }
2569 }
2570
Christopher Tate2efd2db2011-07-19 16:32:49 -07002571 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2572 OutputStream ofstream) throws Exception {
2573 // User key will be used to encrypt the master key.
2574 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002575 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002576 PBKDF2_HASH_ROUNDS);
2577
2578 // the master key is random for each backup
2579 byte[] masterPw = new byte[256 / 8];
2580 mRng.nextBytes(masterPw);
2581 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2582
2583 // primary encryption of the datastream with the random key
2584 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2585 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2586 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2587 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2588
2589 // line 4: name of encryption algorithm
2590 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2591 headerbuf.append('\n');
2592 // line 5: user password salt [hex]
2593 headerbuf.append(byteArrayToHex(newUserSalt));
2594 headerbuf.append('\n');
2595 // line 6: master key checksum salt [hex]
2596 headerbuf.append(byteArrayToHex(checksumSalt));
2597 headerbuf.append('\n');
2598 // line 7: number of PBKDF2 rounds used [decimal]
2599 headerbuf.append(PBKDF2_HASH_ROUNDS);
2600 headerbuf.append('\n');
2601
2602 // line 8: IV of the user key [hex]
2603 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2604 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2605
2606 byte[] IV = mkC.getIV();
2607 headerbuf.append(byteArrayToHex(IV));
2608 headerbuf.append('\n');
2609
2610 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2611 // [byte] IV length = Niv
2612 // [array of Niv bytes] IV itself
2613 // [byte] master key length = Nmk
2614 // [array of Nmk bytes] master key itself
2615 // [byte] MK checksum hash length = Nck
2616 // [array of Nck bytes] master key checksum hash
2617 //
2618 // The checksum is the (master key + checksum salt), run through the
2619 // stated number of PBKDF2 rounds
2620 IV = c.getIV();
2621 byte[] mk = masterKeySpec.getEncoded();
2622 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2623 checksumSalt, PBKDF2_HASH_ROUNDS);
2624
2625 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2626 + checksum.length + 3);
2627 DataOutputStream mkOut = new DataOutputStream(blob);
2628 mkOut.writeByte(IV.length);
2629 mkOut.write(IV);
2630 mkOut.writeByte(mk.length);
2631 mkOut.write(mk);
2632 mkOut.writeByte(checksum.length);
2633 mkOut.write(checksum);
2634 mkOut.flush();
2635 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2636 headerbuf.append(byteArrayToHex(encryptedMk));
2637 headerbuf.append('\n');
2638
2639 return finalOutput;
2640 }
2641
2642 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002643 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002644 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2645
2646 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2647 IApplicationThread.BACKUP_MODE_FULL);
2648 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002649 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002650 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002651 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002652
Christopher Tateb0628bf2011-06-02 15:08:13 -07002653 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002654 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002655 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002656 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002657 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2658 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2659 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2660
Christopher Tate73d73692012-01-20 17:11:31 -08002661 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002662
Christopher Tate7926a692011-07-11 11:31:57 -07002663 final int token = generateToken();
2664 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002665 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002666 pipes[1].close(); // the runner has dup'd it
2667 pipes[1] = null;
2668 Thread t = new Thread(runner);
2669 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002670
Christopher Tate7926a692011-07-11 11:31:57 -07002671 // Now pull data from the app and stuff it into the compressor
2672 try {
2673 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2674 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002675
Christopher Tate7926a692011-07-11 11:31:57 -07002676 byte[] buffer = new byte[16 * 1024];
2677 int chunkTotal;
2678 while ((chunkTotal = in.readInt()) > 0) {
2679 while (chunkTotal > 0) {
2680 int toRead = (chunkTotal > buffer.length)
2681 ? buffer.length : chunkTotal;
2682 int nRead = in.read(buffer, 0, toRead);
2683 out.write(buffer, 0, nRead);
2684 chunkTotal -= nRead;
2685 }
2686 }
2687 } catch (IOException e) {
2688 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002689 }
2690
Christopher Tateb0628bf2011-06-02 15:08:13 -07002691 if (!waitUntilOperationComplete(token)) {
2692 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2693 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002694 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002695 }
Christopher Tate7926a692011-07-11 11:31:57 -07002696
Christopher Tateb0628bf2011-06-02 15:08:13 -07002697 } catch (IOException e) {
2698 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002699 } finally {
2700 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002701 // flush after every package
2702 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002703 if (pipes != null) {
2704 if (pipes[0] != null) pipes[0].close();
2705 if (pipes[1] != null) pipes[1].close();
2706 }
Christopher Tate7926a692011-07-11 11:31:57 -07002707 } catch (IOException e) {
2708 Slog.w(TAG, "Error bringing down backup stack");
2709 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002710 }
2711 } else {
2712 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2713 }
2714 tearDown(pkg);
2715 }
2716
Christopher Tate79ec80d2011-06-24 14:58:49 -07002717 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2718 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2719 final String appSourceDir = pkg.applicationInfo.sourceDir;
2720 final String apkDir = new File(appSourceDir).getParent();
2721 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2722 apkDir, appSourceDir, output);
2723
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002724 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2725 // doesn't have access to external storage.
2726
Christopher Tate79ec80d2011-06-24 14:58:49 -07002727 // Save associated .obb content if it exists and we did save the apk
2728 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002729 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2730 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002731 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002732 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002733 File[] obbFiles = obbDir.listFiles();
2734 if (obbFiles != null) {
2735 final String obbDirName = obbDir.getAbsolutePath();
2736 for (File obb : obbFiles) {
2737 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2738 obbDirName, obb.getAbsolutePath(), output);
2739 }
2740 }
2741 }
2742 }
2743
Christopher Tate6853fcf2011-08-10 17:52:21 -07002744 private void finalizeBackup(OutputStream out) {
2745 try {
2746 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2747 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2748 out.write(eof);
2749 } catch (IOException e) {
2750 Slog.w(TAG, "Error attempting to finalize backup stream");
2751 }
2752 }
2753
Christopher Tate4a627c72011-04-01 14:43:32 -07002754 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2755 throws IOException {
2756 // Manifest format. All data are strings ending in LF:
2757 // BACKUP_MANIFEST_VERSION, currently 1
2758 //
2759 // Version 1:
2760 // package name
2761 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002762 // platform versionCode
2763 // getInstallerPackageName() for this package (maybe empty)
2764 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002765 // number of signatures == N
2766 // N*: signature byte array in ascii format per Signature.toCharsString()
2767 StringBuilder builder = new StringBuilder(4096);
2768 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2769
2770 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2771 printer.println(pkg.packageName);
2772 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002773 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2774
2775 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2776 printer.println((installerName != null) ? installerName : "");
2777
Christopher Tate4a627c72011-04-01 14:43:32 -07002778 printer.println(withApk ? "1" : "0");
2779 if (pkg.signatures == null) {
2780 printer.println("0");
2781 } else {
2782 printer.println(Integer.toString(pkg.signatures.length));
2783 for (Signature sig : pkg.signatures) {
2784 printer.println(sig.toCharsString());
2785 }
2786 }
2787
2788 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002789 outstream.write(builder.toString().getBytes());
2790 outstream.close();
2791 }
2792
2793 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002794 if (pkg != null) {
2795 final ApplicationInfo app = pkg.applicationInfo;
2796 if (app != null) {
2797 try {
2798 // unbind and tidy up even on timeout or failure, just in case
2799 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002800
Christopher Tateb0628bf2011-06-02 15:08:13 -07002801 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002802 if (app.uid != Process.SYSTEM_UID
2803 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002804 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002805 mActivityManager.killApplicationProcess(app.processName, app.uid);
2806 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002807 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002808 }
2809 } catch (RemoteException e) {
2810 Slog.d(TAG, "Lost app trying to shut down");
2811 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002812 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002813 }
2814 }
2815
2816 // wrappers for observer use
2817 void sendStartBackup() {
2818 if (mObserver != null) {
2819 try {
2820 mObserver.onStartBackup();
2821 } catch (RemoteException e) {
2822 Slog.w(TAG, "full backup observer went away: startBackup");
2823 mObserver = null;
2824 }
2825 }
2826 }
2827
2828 void sendOnBackupPackage(String name) {
2829 if (mObserver != null) {
2830 try {
2831 // TODO: use a more user-friendly name string
2832 mObserver.onBackupPackage(name);
2833 } catch (RemoteException e) {
2834 Slog.w(TAG, "full backup observer went away: backupPackage");
2835 mObserver = null;
2836 }
2837 }
2838 }
2839
2840 void sendEndBackup() {
2841 if (mObserver != null) {
2842 try {
2843 mObserver.onEndBackup();
2844 } catch (RemoteException e) {
2845 Slog.w(TAG, "full backup observer went away: endBackup");
2846 mObserver = null;
2847 }
2848 }
2849 }
2850 }
2851
2852
Christopher Tate75a99702011-05-18 16:28:19 -07002853 // ----- Full restore from a file/socket -----
2854
2855 // Description of a file in the restore datastream
2856 static class FileMetadata {
2857 String packageName; // name of the owning app
2858 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002859 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002860 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2861 String path; // subpath within the semantic domain
2862 long mode; // e.g. 0666 (actually int)
2863 long mtime; // last mod time, UTC time_t (actually int)
2864 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002865
2866 @Override
2867 public String toString() {
2868 StringBuilder sb = new StringBuilder(128);
2869 sb.append("FileMetadata{");
2870 sb.append(packageName); sb.append(',');
2871 sb.append(type); sb.append(',');
2872 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2873 sb.append(size);
2874 sb.append('}');
2875 return sb.toString();
2876 }
Christopher Tate75a99702011-05-18 16:28:19 -07002877 }
2878
2879 enum RestorePolicy {
2880 IGNORE,
2881 ACCEPT,
2882 ACCEPT_IF_APK
2883 }
2884
2885 class PerformFullRestoreTask implements Runnable {
2886 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002887 String mCurrentPassword;
2888 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002889 IFullBackupRestoreObserver mObserver;
2890 AtomicBoolean mLatchObject;
2891 IBackupAgent mAgent;
2892 String mAgentPackage;
2893 ApplicationInfo mTargetApp;
2894 ParcelFileDescriptor[] mPipes = null;
2895
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002896 long mBytes;
2897
Christopher Tate75a99702011-05-18 16:28:19 -07002898 // possible handling states for a given package in the restore dataset
2899 final HashMap<String, RestorePolicy> mPackagePolicies
2900 = new HashMap<String, RestorePolicy>();
2901
2902 // installer package names for each encountered app, derived from the manifests
2903 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2904
2905 // Signatures for a given package found in its manifest file
2906 final HashMap<String, Signature[]> mManifestSignatures
2907 = new HashMap<String, Signature[]>();
2908
2909 // Packages we've already wiped data on when restoring their first file
2910 final HashSet<String> mClearedPackages = new HashSet<String>();
2911
Christopher Tate728a1c42011-07-28 18:03:03 -07002912 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002913 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002914 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002915 mCurrentPassword = curPassword;
2916 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002917 mObserver = observer;
2918 mLatchObject = latch;
2919 mAgent = null;
2920 mAgentPackage = null;
2921 mTargetApp = null;
2922
2923 // Which packages we've already wiped data on. We prepopulate this
2924 // with a whitelist of packages known to be unclearable.
2925 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002926 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002927
Christopher Tate75a99702011-05-18 16:28:19 -07002928 }
2929
2930 class RestoreFileRunnable implements Runnable {
2931 IBackupAgent mAgent;
2932 FileMetadata mInfo;
2933 ParcelFileDescriptor mSocket;
2934 int mToken;
2935
2936 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2937 ParcelFileDescriptor socket, int token) throws IOException {
2938 mAgent = agent;
2939 mInfo = info;
2940 mToken = token;
2941
2942 // This class is used strictly for process-local binder invocations. The
2943 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2944 // do not automatically get a 'dup'ed descriptor that we can can continue
2945 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2946 // before proceeding to do the restore.
2947 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2948 }
2949
2950 @Override
2951 public void run() {
2952 try {
2953 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2954 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2955 mToken, mBackupManagerBinder);
2956 } catch (RemoteException e) {
2957 // never happens; this is used strictly for local binder calls
2958 }
2959 }
2960 }
2961
2962 @Override
2963 public void run() {
2964 Slog.i(TAG, "--- Performing full-dataset restore ---");
2965 sendStartRestore();
2966
Christopher Tateb0628bf2011-06-02 15:08:13 -07002967 // Are we able to restore shared-storage data?
2968 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002969 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002970 }
2971
Christopher Tate2efd2db2011-07-19 16:32:49 -07002972 FileInputStream rawInStream = null;
2973 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002974 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002975 if (hasBackupPassword()) {
2976 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2977 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2978 return;
2979 }
2980 }
2981
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002982 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002983 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002984 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2985 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002986
2987 // First, parse out the unencrypted/uncompressed header
2988 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002989 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002990 final InputStream in;
2991
2992 boolean okay = false;
2993 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2994 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002995 rawDataIn.readFully(streamHeader);
2996 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2997 if (Arrays.equals(magicBytes, streamHeader)) {
2998 // okay, header looks good. now parse out the rest of the fields.
2999 String s = readHeaderLine(rawInStream);
3000 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3001 // okay, it's a version we recognize
3002 s = readHeaderLine(rawInStream);
3003 compressed = (Integer.parseInt(s) != 0);
3004 s = readHeaderLine(rawInStream);
3005 if (s.equals("none")) {
3006 // no more header to parse; we're good to go
3007 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003008 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003009 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3010 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003011 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003012 }
3013 } else Slog.w(TAG, "Archive is encrypted but no password given");
3014 } else Slog.w(TAG, "Wrong header version: " + s);
3015 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003016
3017 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003018 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003019 return;
3020 }
3021
3022 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003023 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003024
3025 boolean didRestore;
3026 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003027 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003028 } while (didRestore);
3029
Christopher Tatec58efa62011-08-01 19:20:14 -07003030 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003031 } catch (IOException e) {
3032 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003033 } finally {
3034 tearDownPipes();
3035 tearDownAgent(mTargetApp);
3036
3037 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003038 if (rawDataIn != null) rawDataIn.close();
3039 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003040 mInputFile.close();
3041 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003042 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003043 /* nothing we can do about this */
3044 }
3045 synchronized (mCurrentOpLock) {
3046 mCurrentOperations.clear();
3047 }
3048 synchronized (mLatchObject) {
3049 mLatchObject.set(true);
3050 mLatchObject.notifyAll();
3051 }
3052 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003053 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003054 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003055 }
3056 }
3057
Christopher Tate7bdb0962011-07-13 19:30:21 -07003058 String readHeaderLine(InputStream in) throws IOException {
3059 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003060 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003061 while ((c = in.read()) >= 0) {
3062 if (c == '\n') break; // consume and discard the newlines
3063 buffer.append((char)c);
3064 }
3065 return buffer.toString();
3066 }
3067
Christopher Tate2efd2db2011-07-19 16:32:49 -07003068 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3069 InputStream result = null;
3070 try {
3071 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3072
3073 String userSaltHex = readHeaderLine(rawInStream); // 5
3074 byte[] userSalt = hexToByteArray(userSaltHex);
3075
3076 String ckSaltHex = readHeaderLine(rawInStream); // 6
3077 byte[] ckSalt = hexToByteArray(ckSaltHex);
3078
3079 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3080 String userIvHex = readHeaderLine(rawInStream); // 8
3081
3082 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3083
3084 // decrypt the master key blob
3085 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003086 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003087 rounds);
3088 byte[] IV = hexToByteArray(userIvHex);
3089 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3090 c.init(Cipher.DECRYPT_MODE,
3091 new SecretKeySpec(userKey.getEncoded(), "AES"),
3092 ivSpec);
3093 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3094 byte[] mkBlob = c.doFinal(mkCipher);
3095
3096 // first, the master key IV
3097 int offset = 0;
3098 int len = mkBlob[offset++];
3099 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3100 offset += len;
3101 // then the master key itself
3102 len = mkBlob[offset++];
3103 byte[] mk = Arrays.copyOfRange(mkBlob,
3104 offset, offset + len);
3105 offset += len;
3106 // and finally the master key checksum hash
3107 len = mkBlob[offset++];
3108 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3109 offset, offset + len);
3110
3111 // now validate the decrypted master key against the checksum
3112 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3113 if (Arrays.equals(calculatedCk, mkChecksum)) {
3114 ivSpec = new IvParameterSpec(IV);
3115 c.init(Cipher.DECRYPT_MODE,
3116 new SecretKeySpec(mk, "AES"),
3117 ivSpec);
3118 // Only if all of the above worked properly will 'result' be assigned
3119 result = new CipherInputStream(rawInStream, c);
3120 } else Slog.w(TAG, "Incorrect password");
3121 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3122 } catch (InvalidAlgorithmParameterException e) {
3123 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3124 } catch (BadPaddingException e) {
3125 // This case frequently occurs when the wrong password is used to decrypt
3126 // the master key. Use the identical "incorrect password" log text as is
3127 // used in the checksum failure log in order to avoid providing additional
3128 // information to an attacker.
3129 Slog.w(TAG, "Incorrect password");
3130 } catch (IllegalBlockSizeException e) {
3131 Slog.w(TAG, "Invalid block size in master key");
3132 } catch (NoSuchAlgorithmException e) {
3133 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3134 } catch (NoSuchPaddingException e) {
3135 Slog.e(TAG, "Needed padding mechanism unavailable!");
3136 } catch (InvalidKeyException e) {
3137 Slog.w(TAG, "Illegal password; aborting");
3138 } catch (NumberFormatException e) {
3139 Slog.w(TAG, "Can't parse restore data header");
3140 } catch (IOException e) {
3141 Slog.w(TAG, "Can't read input header");
3142 }
3143
3144 return result;
3145 }
3146
Christopher Tate75a99702011-05-18 16:28:19 -07003147 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3148 FileMetadata info;
3149 try {
3150 info = readTarHeaders(instream);
3151 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003152 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003153 dumpFileMetadata(info);
3154 }
3155
3156 final String pkg = info.packageName;
3157 if (!pkg.equals(mAgentPackage)) {
3158 // okay, change in package; set up our various
3159 // bookkeeping if we haven't seen it yet
3160 if (!mPackagePolicies.containsKey(pkg)) {
3161 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3162 }
3163
3164 // Clean up the previous agent relationship if necessary,
3165 // and let the observer know we're considering a new app.
3166 if (mAgent != null) {
3167 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3168 tearDownPipes();
3169 tearDownAgent(mTargetApp);
3170 mTargetApp = null;
3171 mAgentPackage = null;
3172 }
3173 }
3174
3175 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3176 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3177 mPackageInstallers.put(pkg, info.installerPackageName);
3178 // We've read only the manifest content itself at this point,
3179 // so consume the footer before looping around to the next
3180 // input file
3181 skipTarPadding(info.size, instream);
3182 sendOnRestorePackage(pkg);
3183 } else {
3184 // Non-manifest, so it's actual file data. Is this a package
3185 // we're ignoring?
3186 boolean okay = true;
3187 RestorePolicy policy = mPackagePolicies.get(pkg);
3188 switch (policy) {
3189 case IGNORE:
3190 okay = false;
3191 break;
3192
3193 case ACCEPT_IF_APK:
3194 // If we're in accept-if-apk state, then the first file we
3195 // see MUST be the apk.
3196 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3197 if (DEBUG) Slog.d(TAG, "APK file; installing");
3198 // Try to install the app.
3199 String installerName = mPackageInstallers.get(pkg);
3200 okay = installApk(info, installerName, instream);
3201 // good to go; promote to ACCEPT
3202 mPackagePolicies.put(pkg, (okay)
3203 ? RestorePolicy.ACCEPT
3204 : RestorePolicy.IGNORE);
3205 // At this point we've consumed this file entry
3206 // ourselves, so just strip the tar footer and
3207 // go on to the next file in the input stream
3208 skipTarPadding(info.size, instream);
3209 return true;
3210 } else {
3211 // File data before (or without) the apk. We can't
3212 // handle it coherently in this case so ignore it.
3213 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3214 okay = false;
3215 }
3216 break;
3217
3218 case ACCEPT:
3219 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3220 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3221 // we can take the data without the apk, so we
3222 // *want* to do so. skip the apk by declaring this
3223 // one file not-okay without changing the restore
3224 // policy for the package.
3225 okay = false;
3226 }
3227 break;
3228
3229 default:
3230 // Something has gone dreadfully wrong when determining
3231 // the restore policy from the manifest. Ignore the
3232 // rest of this package's data.
3233 Slog.e(TAG, "Invalid policy from manifest");
3234 okay = false;
3235 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3236 break;
3237 }
3238
3239 // If the policy is satisfied, go ahead and set up to pipe the
3240 // data to the agent.
3241 if (DEBUG && okay && mAgent != null) {
3242 Slog.i(TAG, "Reusing existing agent instance");
3243 }
3244 if (okay && mAgent == null) {
3245 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3246
3247 try {
3248 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3249
3250 // If we haven't sent any data to this app yet, we probably
3251 // need to clear it first. Check that.
3252 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003253 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003254 // responsible for coherently managing a full
3255 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003256 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003257 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3258 clearApplicationDataSynchronous(pkg);
3259 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003260 if (DEBUG) Slog.d(TAG, "backup agent ("
3261 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003262 }
3263 mClearedPackages.add(pkg);
3264 } else {
3265 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3266 }
3267
3268 // All set; now set up the IPC and launch the agent
3269 setUpPipes();
3270 mAgent = bindToAgentSynchronous(mTargetApp,
3271 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3272 mAgentPackage = pkg;
3273 } catch (IOException e) {
3274 // fall through to error handling
3275 } catch (NameNotFoundException e) {
3276 // fall through to error handling
3277 }
3278
3279 if (mAgent == null) {
3280 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3281 okay = false;
3282 tearDownPipes();
3283 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3284 }
3285 }
3286
3287 // Sanity check: make sure we never give data to the wrong app. This
3288 // should never happen but a little paranoia here won't go amiss.
3289 if (okay && !pkg.equals(mAgentPackage)) {
3290 Slog.e(TAG, "Restoring data for " + pkg
3291 + " but agent is for " + mAgentPackage);
3292 okay = false;
3293 }
3294
3295 // At this point we have an agent ready to handle the full
3296 // restore data as well as a pipe for sending data to
3297 // that agent. Tell the agent to start reading from the
3298 // pipe.
3299 if (okay) {
3300 boolean agentSuccess = true;
3301 long toCopy = info.size;
3302 final int token = generateToken();
3303 try {
3304 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3305 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003306 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003307 // fire up the app's agent listening on the socket. If
3308 // the agent is running in the system process we can't
3309 // just invoke it asynchronously, so we provide a thread
3310 // for it here.
3311 if (mTargetApp.processName.equals("system")) {
3312 Slog.d(TAG, "system process agent - spinning a thread");
3313 RestoreFileRunnable runner = new RestoreFileRunnable(
3314 mAgent, info, mPipes[0], token);
3315 new Thread(runner).start();
3316 } else {
3317 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3318 info.domain, info.path, info.mode, info.mtime,
3319 token, mBackupManagerBinder);
3320 }
3321 } catch (IOException e) {
3322 // couldn't dup the socket for a process-local restore
3323 Slog.d(TAG, "Couldn't establish restore");
3324 agentSuccess = false;
3325 okay = false;
3326 } catch (RemoteException e) {
3327 // whoops, remote agent went away. We'll eat the content
3328 // ourselves, then, and not copy it over.
3329 Slog.e(TAG, "Agent crashed during full restore");
3330 agentSuccess = false;
3331 okay = false;
3332 }
3333
3334 // Copy over the data if the agent is still good
3335 if (okay) {
3336 boolean pipeOkay = true;
3337 FileOutputStream pipe = new FileOutputStream(
3338 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003339 while (toCopy > 0) {
3340 int toRead = (toCopy > buffer.length)
3341 ? buffer.length : (int)toCopy;
3342 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003343 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003344 if (nRead <= 0) break;
3345 toCopy -= nRead;
3346
3347 // send it to the output pipe as long as things
3348 // are still good
3349 if (pipeOkay) {
3350 try {
3351 pipe.write(buffer, 0, nRead);
3352 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003353 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003354 pipeOkay = false;
3355 }
3356 }
3357 }
3358
3359 // done sending that file! Now we just need to consume
3360 // the delta from info.size to the end of block.
3361 skipTarPadding(info.size, instream);
3362
3363 // and now that we've sent it all, wait for the remote
3364 // side to acknowledge receipt
3365 agentSuccess = waitUntilOperationComplete(token);
3366 }
3367
3368 // okay, if the remote end failed at any point, deal with
3369 // it by ignoring the rest of the restore on it
3370 if (!agentSuccess) {
3371 mBackupHandler.removeMessages(MSG_TIMEOUT);
3372 tearDownPipes();
3373 tearDownAgent(mTargetApp);
3374 mAgent = null;
3375 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3376 }
3377 }
3378
3379 // Problems setting up the agent communication, or an already-
3380 // ignored package: skip to the next tar stream entry by
3381 // reading and discarding this file.
3382 if (!okay) {
3383 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3384 long bytesToConsume = (info.size + 511) & ~511;
3385 while (bytesToConsume > 0) {
3386 int toRead = (bytesToConsume > buffer.length)
3387 ? buffer.length : (int)bytesToConsume;
3388 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003389 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003390 if (nRead <= 0) break;
3391 bytesToConsume -= nRead;
3392 }
3393 }
3394 }
3395 }
3396 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003397 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003398 // treat as EOF
3399 info = null;
3400 }
3401
3402 return (info != null);
3403 }
3404
3405 void setUpPipes() throws IOException {
3406 mPipes = ParcelFileDescriptor.createPipe();
3407 }
3408
3409 void tearDownPipes() {
3410 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003411 try {
3412 mPipes[0].close();
3413 mPipes[0] = null;
3414 mPipes[1].close();
3415 mPipes[1] = null;
3416 } catch (IOException e) {
3417 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003418 }
3419 mPipes = null;
3420 }
3421 }
3422
3423 void tearDownAgent(ApplicationInfo app) {
3424 if (mAgent != null) {
3425 try {
3426 // unbind and tidy up even on timeout or failure, just in case
3427 mActivityManager.unbindBackupAgent(app);
3428
3429 // The agent was running with a stub Application object, so shut it down.
3430 // !!! We hardcode the confirmation UI's package name here rather than use a
3431 // manifest flag! TODO something less direct.
3432 if (app.uid != Process.SYSTEM_UID
3433 && !app.packageName.equals("com.android.backupconfirm")) {
3434 if (DEBUG) Slog.d(TAG, "Killing host process");
3435 mActivityManager.killApplicationProcess(app.processName, app.uid);
3436 } else {
3437 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3438 }
3439 } catch (RemoteException e) {
3440 Slog.d(TAG, "Lost app trying to shut down");
3441 }
3442 mAgent = null;
3443 }
3444 }
3445
3446 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3447 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003448 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003449 int mResult;
3450
3451 public void reset() {
3452 synchronized (mDone) {
3453 mDone.set(false);
3454 }
3455 }
3456
3457 public void waitForCompletion() {
3458 synchronized (mDone) {
3459 while (mDone.get() == false) {
3460 try {
3461 mDone.wait();
3462 } catch (InterruptedException e) { }
3463 }
3464 }
3465 }
3466
3467 int getResult() {
3468 return mResult;
3469 }
3470
3471 @Override
3472 public void packageInstalled(String packageName, int returnCode)
3473 throws RemoteException {
3474 synchronized (mDone) {
3475 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003476 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003477 mDone.set(true);
3478 mDone.notifyAll();
3479 }
3480 }
3481 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003482
3483 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3484 final AtomicBoolean mDone = new AtomicBoolean();
3485 int mResult;
3486
3487 public void reset() {
3488 synchronized (mDone) {
3489 mDone.set(false);
3490 }
3491 }
3492
3493 public void waitForCompletion() {
3494 synchronized (mDone) {
3495 while (mDone.get() == false) {
3496 try {
3497 mDone.wait();
3498 } catch (InterruptedException e) { }
3499 }
3500 }
3501 }
3502
3503 @Override
3504 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3505 synchronized (mDone) {
3506 mResult = returnCode;
3507 mDone.set(true);
3508 mDone.notifyAll();
3509 }
3510 }
3511 }
3512
Christopher Tate75a99702011-05-18 16:28:19 -07003513 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003514 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003515
3516 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3517 boolean okay = true;
3518
3519 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3520
3521 // The file content is an .apk file. Copy it out to a staging location and
3522 // attempt to install it.
3523 File apkFile = new File(mDataDir, info.packageName);
3524 try {
3525 FileOutputStream apkStream = new FileOutputStream(apkFile);
3526 byte[] buffer = new byte[32 * 1024];
3527 long size = info.size;
3528 while (size > 0) {
3529 long toRead = (buffer.length < size) ? buffer.length : size;
3530 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003531 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003532 apkStream.write(buffer, 0, didRead);
3533 size -= didRead;
3534 }
3535 apkStream.close();
3536
3537 // make sure the installer can read it
3538 apkFile.setReadable(true, false);
3539
3540 // Now install it
3541 Uri packageUri = Uri.fromFile(apkFile);
3542 mInstallObserver.reset();
3543 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003544 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3545 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003546 mInstallObserver.waitForCompletion();
3547
3548 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3549 // The only time we continue to accept install of data even if the
3550 // apk install failed is if we had already determined that we could
3551 // accept the data regardless.
3552 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3553 okay = false;
3554 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003555 } else {
3556 // Okay, the install succeeded. Make sure it was the right app.
3557 boolean uninstall = false;
3558 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3559 Slog.w(TAG, "Restore stream claimed to include apk for "
3560 + info.packageName + " but apk was really "
3561 + mInstallObserver.mPackageName);
3562 // delete the package we just put in place; it might be fraudulent
3563 okay = false;
3564 uninstall = true;
3565 } else {
3566 try {
3567 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3568 PackageManager.GET_SIGNATURES);
3569 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3570 Slog.w(TAG, "Restore stream contains apk of package "
3571 + info.packageName + " but it disallows backup/restore");
3572 okay = false;
3573 } else {
3574 // So far so good -- do the signatures match the manifest?
3575 Signature[] sigs = mManifestSignatures.get(info.packageName);
3576 if (!signaturesMatch(sigs, pkg)) {
3577 Slog.w(TAG, "Installed app " + info.packageName
3578 + " signatures do not match restore manifest");
3579 okay = false;
3580 uninstall = true;
3581 }
3582 }
3583 } catch (NameNotFoundException e) {
3584 Slog.w(TAG, "Install of package " + info.packageName
3585 + " succeeded but now not found");
3586 okay = false;
3587 }
3588 }
3589
3590 // If we're not okay at this point, we need to delete the package
3591 // that we just installed.
3592 if (uninstall) {
3593 mDeleteObserver.reset();
3594 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3595 mDeleteObserver, 0);
3596 mDeleteObserver.waitForCompletion();
3597 }
Christopher Tate75a99702011-05-18 16:28:19 -07003598 }
3599 } catch (IOException e) {
3600 Slog.e(TAG, "Unable to transcribe restored apk for install");
3601 okay = false;
3602 } finally {
3603 apkFile.delete();
3604 }
3605
3606 return okay;
3607 }
3608
3609 // Given an actual file content size, consume the post-content padding mandated
3610 // by the tar format.
3611 void skipTarPadding(long size, InputStream instream) throws IOException {
3612 long partial = (size + 512) % 512;
3613 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003614 final int needed = 512 - (int)partial;
3615 byte[] buffer = new byte[needed];
3616 if (readExactly(instream, buffer, 0, needed) == needed) {
3617 mBytes += needed;
3618 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003619 }
3620 }
3621
3622 // Returns a policy constant; takes a buffer arg to reduce memory churn
3623 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3624 throws IOException {
3625 // Fail on suspiciously large manifest files
3626 if (info.size > 64 * 1024) {
3627 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3628 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003629
Christopher Tate75a99702011-05-18 16:28:19 -07003630 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003631 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3632 mBytes += info.size;
3633 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003634
3635 RestorePolicy policy = RestorePolicy.IGNORE;
3636 String[] str = new String[1];
3637 int offset = 0;
3638
3639 try {
3640 offset = extractLine(buffer, offset, str);
3641 int version = Integer.parseInt(str[0]);
3642 if (version == BACKUP_MANIFEST_VERSION) {
3643 offset = extractLine(buffer, offset, str);
3644 String manifestPackage = str[0];
3645 // TODO: handle <original-package>
3646 if (manifestPackage.equals(info.packageName)) {
3647 offset = extractLine(buffer, offset, str);
3648 version = Integer.parseInt(str[0]); // app version
3649 offset = extractLine(buffer, offset, str);
3650 int platformVersion = Integer.parseInt(str[0]);
3651 offset = extractLine(buffer, offset, str);
3652 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3653 offset = extractLine(buffer, offset, str);
3654 boolean hasApk = str[0].equals("1");
3655 offset = extractLine(buffer, offset, str);
3656 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003657 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003658 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003659 for (int i = 0; i < numSigs; i++) {
3660 offset = extractLine(buffer, offset, str);
3661 sigs[i] = new Signature(str[0]);
3662 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003663 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003664
3665 // Okay, got the manifest info we need...
3666 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003667 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3668 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003669 // Fall through to IGNORE if the app explicitly disallows backup
3670 final int flags = pkgInfo.applicationInfo.flags;
3671 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3672 // Verify signatures against any installed version; if they
3673 // don't match, then we fall though and ignore the data. The
3674 // signatureMatch() method explicitly ignores the signature
3675 // check for packages installed on the system partition, because
3676 // such packages are signed with the platform cert instead of
3677 // the app developer's cert, so they're different on every
3678 // device.
3679 if (signaturesMatch(sigs, pkgInfo)) {
3680 if (pkgInfo.versionCode >= version) {
3681 Slog.i(TAG, "Sig + version match; taking data");
3682 policy = RestorePolicy.ACCEPT;
3683 } else {
3684 // The data is from a newer version of the app than
3685 // is presently installed. That means we can only
3686 // use it if the matching apk is also supplied.
3687 Slog.d(TAG, "Data version " + version
3688 + " is newer than installed version "
3689 + pkgInfo.versionCode + " - requiring apk");
3690 policy = RestorePolicy.ACCEPT_IF_APK;
3691 }
Christopher Tate75a99702011-05-18 16:28:19 -07003692 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003693 Slog.w(TAG, "Restore manifest signatures do not match "
3694 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003695 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003696 } else {
3697 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3698 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003699 }
3700 } catch (NameNotFoundException e) {
3701 // Okay, the target app isn't installed. We can process
3702 // the restore properly only if the dataset provides the
3703 // apk file and we can successfully install it.
3704 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3705 + " not installed; requiring apk in dataset");
3706 policy = RestorePolicy.ACCEPT_IF_APK;
3707 }
3708
3709 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3710 Slog.i(TAG, "Cannot restore package " + info.packageName
3711 + " without the matching .apk");
3712 }
3713 } else {
3714 Slog.i(TAG, "Missing signature on backed-up package "
3715 + info.packageName);
3716 }
3717 } else {
3718 Slog.i(TAG, "Expected package " + info.packageName
3719 + " but restore manifest claims " + manifestPackage);
3720 }
3721 } else {
3722 Slog.i(TAG, "Unknown restore manifest version " + version
3723 + " for package " + info.packageName);
3724 }
3725 } catch (NumberFormatException e) {
3726 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003727 } catch (IllegalArgumentException e) {
3728 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003729 }
3730
3731 return policy;
3732 }
3733
3734 // Builds a line from a byte buffer starting at 'offset', and returns
3735 // the index of the next unconsumed data in the buffer.
3736 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3737 final int end = buffer.length;
3738 if (offset >= end) throw new IOException("Incomplete data");
3739
3740 int pos;
3741 for (pos = offset; pos < end; pos++) {
3742 byte c = buffer[pos];
3743 // at LF we declare end of line, and return the next char as the
3744 // starting point for the next time through
3745 if (c == '\n') {
3746 break;
3747 }
3748 }
3749 outStr[0] = new String(buffer, offset, pos - offset);
3750 pos++; // may be pointing an extra byte past the end but that's okay
3751 return pos;
3752 }
3753
3754 void dumpFileMetadata(FileMetadata info) {
3755 if (DEBUG) {
3756 StringBuilder b = new StringBuilder(128);
3757
3758 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003759 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003760 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3761 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3762 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3763 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3764 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3765 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3766 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3767 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3768 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3769 b.append(String.format(" %9d ", info.size));
3770
3771 Date stamp = new Date(info.mtime);
3772 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3773
3774 b.append(info.packageName);
3775 b.append(" :: ");
3776 b.append(info.domain);
3777 b.append(" :: ");
3778 b.append(info.path);
3779
3780 Slog.i(TAG, b.toString());
3781 }
3782 }
3783 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3784 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3785 byte[] block = new byte[512];
3786 FileMetadata info = null;
3787
3788 boolean gotHeader = readTarHeader(instream, block);
3789 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003790 try {
3791 // okay, presume we're okay, and extract the various metadata
3792 info = new FileMetadata();
3793 info.size = extractRadix(block, 124, 12, 8);
3794 info.mtime = extractRadix(block, 136, 12, 8);
3795 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003796
Christopher Tate2efd2db2011-07-19 16:32:49 -07003797 info.path = extractString(block, 345, 155); // prefix
3798 String path = extractString(block, 0, 100);
3799 if (path.length() > 0) {
3800 if (info.path.length() > 0) info.path += '/';
3801 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003802 }
Christopher Tate75a99702011-05-18 16:28:19 -07003803
Christopher Tate2efd2db2011-07-19 16:32:49 -07003804 // tar link indicator field: 1 byte at offset 156 in the header.
3805 int typeChar = block[156];
3806 if (typeChar == 'x') {
3807 // pax extended header, so we need to read that
3808 gotHeader = readPaxExtendedHeader(instream, info);
3809 if (gotHeader) {
3810 // and after a pax extended header comes another real header -- read
3811 // that to find the real file type
3812 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003813 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003814 if (!gotHeader) throw new IOException("Bad or missing pax header");
3815
3816 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003817 }
Christopher Tate75a99702011-05-18 16:28:19 -07003818
Christopher Tate2efd2db2011-07-19 16:32:49 -07003819 switch (typeChar) {
3820 case '0': info.type = BackupAgent.TYPE_FILE; break;
3821 case '5': {
3822 info.type = BackupAgent.TYPE_DIRECTORY;
3823 if (info.size != 0) {
3824 Slog.w(TAG, "Directory entry with nonzero size in header");
3825 info.size = 0;
3826 }
3827 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003828 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003829 case 0: {
3830 // presume EOF
3831 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3832 return null;
3833 }
3834 default: {
3835 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3836 throw new IOException("Unknown entity type " + typeChar);
3837 }
Christopher Tate75a99702011-05-18 16:28:19 -07003838 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003839
3840 // Parse out the path
3841 //
3842 // first: apps/shared/unrecognized
3843 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3844 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3845 // File in shared storage. !!! TODO: implement this.
3846 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003847 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003848 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3849 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3850 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3851 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3852 // App content! Parse out the package name and domain
3853
3854 // strip the apps/ prefix
3855 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3856
3857 // extract the package name
3858 int slash = info.path.indexOf('/');
3859 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3860 info.packageName = info.path.substring(0, slash);
3861 info.path = info.path.substring(slash+1);
3862
3863 // if it's a manifest we're done, otherwise parse out the domains
3864 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3865 slash = info.path.indexOf('/');
3866 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3867 info.domain = info.path.substring(0, slash);
3868 // validate that it's one of the domains we understand
3869 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3870 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3871 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3872 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3873 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3874 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3875 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3876 throw new IOException("Unrecognized domain " + info.domain);
3877 }
3878
3879 info.path = info.path.substring(slash + 1);
3880 }
3881 }
3882 } catch (IOException e) {
3883 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003884 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003885 HEXLOG(block);
3886 }
3887 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003888 }
3889 }
3890 return info;
3891 }
3892
Christopher Tate2efd2db2011-07-19 16:32:49 -07003893 private void HEXLOG(byte[] block) {
3894 int offset = 0;
3895 int todo = block.length;
3896 StringBuilder buf = new StringBuilder(64);
3897 while (todo > 0) {
3898 buf.append(String.format("%04x ", offset));
3899 int numThisLine = (todo > 16) ? 16 : todo;
3900 for (int i = 0; i < numThisLine; i++) {
3901 buf.append(String.format("%02x ", block[offset+i]));
3902 }
3903 Slog.i("hexdump", buf.toString());
3904 buf.setLength(0);
3905 todo -= numThisLine;
3906 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003907 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003908 }
3909
Christopher Tate6853fcf2011-08-10 17:52:21 -07003910 // Read exactly the given number of bytes into a buffer at the stated offset.
3911 // Returns false if EOF is encountered before the requested number of bytes
3912 // could be read.
3913 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3914 throws IOException {
3915 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3916
3917 int soFar = 0;
3918 while (soFar < size) {
3919 int nRead = in.read(buffer, offset + soFar, size - soFar);
3920 if (nRead <= 0) {
3921 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3922 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003923 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003924 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003925 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003926 return soFar;
3927 }
3928
3929 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3930 final int got = readExactly(instream, block, 0, 512);
3931 if (got == 0) return false; // Clean EOF
3932 if (got < 512) throw new IOException("Unable to read full block header");
3933 mBytes += 512;
3934 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003935 }
3936
3937 // overwrites 'info' fields based on the pax extended header
3938 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3939 throws IOException {
3940 // We should never see a pax extended header larger than this
3941 if (info.size > 32*1024) {
3942 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3943 + " - aborting");
3944 throw new IOException("Sanity failure: pax header size " + info.size);
3945 }
3946
3947 // read whole blocks, not just the content size
3948 int numBlocks = (int)((info.size + 511) >> 9);
3949 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003950 if (readExactly(instream, data, 0, data.length) < data.length) {
3951 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003952 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003953 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003954
3955 final int contentSize = (int) info.size;
3956 int offset = 0;
3957 do {
3958 // extract the line at 'offset'
3959 int eol = offset+1;
3960 while (eol < contentSize && data[eol] != ' ') eol++;
3961 if (eol >= contentSize) {
3962 // error: we just hit EOD looking for the end of the size field
3963 throw new IOException("Invalid pax data");
3964 }
3965 // eol points to the space between the count and the key
3966 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3967 int key = eol + 1; // start of key=value
3968 eol = offset + linelen - 1; // trailing LF
3969 int value;
3970 for (value = key+1; data[value] != '=' && value <= eol; value++);
3971 if (value > eol) {
3972 throw new IOException("Invalid pax declaration");
3973 }
3974
3975 // pax requires that key/value strings be in UTF-8
3976 String keyStr = new String(data, key, value-key, "UTF-8");
3977 // -1 to strip the trailing LF
3978 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3979
3980 if ("path".equals(keyStr)) {
3981 info.path = valStr;
3982 } else if ("size".equals(keyStr)) {
3983 info.size = Long.parseLong(valStr);
3984 } else {
3985 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3986 }
3987
3988 offset += linelen;
3989 } while (offset < contentSize);
3990
3991 return true;
3992 }
3993
3994 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3995 throws IOException {
3996 long value = 0;
3997 final int end = offset + maxChars;
3998 for (int i = offset; i < end; i++) {
3999 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004000 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004001 if (b == 0 || b == ' ') break;
4002 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004003 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004004 }
4005 value = radix * value + (b - '0');
4006 }
4007 return value;
4008 }
4009
4010 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4011 final int end = offset + maxChars;
4012 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004013 // tar string fields terminate early with a NUL
4014 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004015 return new String(data, offset, eos-offset, "US-ASCII");
4016 }
4017
4018 void sendStartRestore() {
4019 if (mObserver != null) {
4020 try {
4021 mObserver.onStartRestore();
4022 } catch (RemoteException e) {
4023 Slog.w(TAG, "full restore observer went away: startRestore");
4024 mObserver = null;
4025 }
4026 }
4027 }
4028
4029 void sendOnRestorePackage(String name) {
4030 if (mObserver != null) {
4031 try {
4032 // TODO: use a more user-friendly name string
4033 mObserver.onRestorePackage(name);
4034 } catch (RemoteException e) {
4035 Slog.w(TAG, "full restore observer went away: restorePackage");
4036 mObserver = null;
4037 }
4038 }
4039 }
4040
4041 void sendEndRestore() {
4042 if (mObserver != null) {
4043 try {
4044 mObserver.onEndRestore();
4045 } catch (RemoteException e) {
4046 Slog.w(TAG, "full restore observer went away: endRestore");
4047 mObserver = null;
4048 }
4049 }
4050 }
4051 }
4052
Christopher Tatedf01dea2009-06-09 20:45:02 -07004053 // ----- Restore handling -----
4054
Christopher Tate78dd4a72009-11-04 11:49:08 -08004055 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4056 // If the target resides on the system partition, we allow it to restore
4057 // data from the like-named package in a restore set even if the signatures
4058 // do not match. (Unlike general applications, those flashed to the system
4059 // partition will be signed with the device's platform certificate, so on
4060 // different phones the same system app will have different signatures.)
4061 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004062 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004063 return true;
4064 }
4065
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004066 // Allow unsigned apps, but not signed on one device and unsigned on the other
4067 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004068 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004069 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004070 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004071 if ((storedSigs == null || storedSigs.length == 0)
4072 && (deviceSigs == null || deviceSigs.length == 0)) {
4073 return true;
4074 }
4075 if (storedSigs == null || deviceSigs == null) {
4076 return false;
4077 }
4078
Christopher Tateabce4e82009-06-18 18:35:32 -07004079 // !!! TODO: this demands that every stored signature match one
4080 // that is present on device, and does not demand the converse.
4081 // Is this this right policy?
4082 int nStored = storedSigs.length;
4083 int nDevice = deviceSigs.length;
4084
4085 for (int i=0; i < nStored; i++) {
4086 boolean match = false;
4087 for (int j=0; j < nDevice; j++) {
4088 if (storedSigs[i].equals(deviceSigs[j])) {
4089 match = true;
4090 break;
4091 }
4092 }
4093 if (!match) {
4094 return false;
4095 }
4096 }
4097 return true;
4098 }
4099
Christopher Tate2982d062011-09-06 20:35:24 -07004100 enum RestoreState {
4101 INITIAL,
4102 DOWNLOAD_DATA,
4103 PM_METADATA,
4104 RUNNING_QUEUE,
4105 FINAL
4106 }
4107
4108 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004109 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004110 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004111 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004112 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004113 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004114 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004115 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004116 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004117 private long mStartRealtime;
4118 private PackageManagerBackupAgent mPmAgent;
4119 private List<PackageInfo> mAgentPackages;
4120 private ArrayList<PackageInfo> mRestorePackages;
4121 private RestoreState mCurrentState;
4122 private int mCount;
4123 private boolean mFinished;
4124 private int mStatus;
4125 private File mBackupDataName;
4126 private File mNewStateName;
4127 private File mSavedStateName;
4128 private ParcelFileDescriptor mBackupData;
4129 private ParcelFileDescriptor mNewState;
4130 private PackageInfo mCurrentPackage;
4131
Christopher Tatedf01dea2009-06-09 20:45:02 -07004132
Christopher Tate5cbbf562009-06-22 16:44:51 -07004133 class RestoreRequest {
4134 public PackageInfo app;
4135 public int storedAppVersion;
4136
4137 RestoreRequest(PackageInfo _app, int _version) {
4138 app = _app;
4139 storedAppVersion = _version;
4140 }
4141 }
4142
Christopher Tate44a27902010-01-27 17:15:49 -08004143 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004144 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004145 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004146 mCurrentState = RestoreState.INITIAL;
4147 mFinished = false;
4148 mPmAgent = null;
4149
Christopher Tatedf01dea2009-06-09 20:45:02 -07004150 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004151 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004152 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004153 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004154 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004155 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004156
Christopher Tate284f1bb2011-07-07 14:31:18 -07004157 if (filterSet != null) {
4158 mFilterSet = new HashSet<String>();
4159 for (String pkg : filterSet) {
4160 mFilterSet.add(pkg);
4161 }
4162 } else {
4163 mFilterSet = null;
4164 }
4165
Christopher Tate5cb400b2009-06-25 16:03:14 -07004166 try {
4167 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4168 } catch (RemoteException e) {
4169 // can't happen; the transport is local
4170 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004171 }
4172
Christopher Tate2982d062011-09-06 20:35:24 -07004173 // Execute one tick of whatever state machine the task implements
4174 @Override
4175 public void execute() {
4176 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4177 switch (mCurrentState) {
4178 case INITIAL:
4179 beginRestore();
4180 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004181
Christopher Tate2982d062011-09-06 20:35:24 -07004182 case DOWNLOAD_DATA:
4183 downloadRestoreData();
4184 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004185
Christopher Tate2982d062011-09-06 20:35:24 -07004186 case PM_METADATA:
4187 restorePmMetadata();
4188 break;
4189
4190 case RUNNING_QUEUE:
4191 restoreNextAgent();
4192 break;
4193
4194 case FINAL:
4195 if (!mFinished) finalizeRestore();
4196 else {
4197 Slog.e(TAG, "Duplicate finish");
4198 }
4199 mFinished = true;
4200 break;
4201 }
4202 }
4203
4204 // Initialize and set up for the PM metadata restore, which comes first
4205 void beginRestore() {
4206 // Don't account time doing the restore as inactivity of the app
4207 // that has opened a restore session.
4208 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4209
4210 // Assume error until we successfully init everything
4211 mStatus = BackupConstants.TRANSPORT_ERROR;
4212
Christopher Tatedf01dea2009-06-09 20:45:02 -07004213 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004214 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004215 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004216
Dan Egnorefe52642009-06-24 00:16:33 -07004217 // Get the list of all packages which have backup enabled.
4218 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004219 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004220 PackageInfo omPackage = new PackageInfo();
4221 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004222 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004223
Christopher Tate2982d062011-09-06 20:35:24 -07004224 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004225 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004226 // if there's a filter set, strip out anything that isn't
4227 // present before proceeding
4228 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004229 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4230 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004231 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004232 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004233 }
4234 }
Christopher Tate2982d062011-09-06 20:35:24 -07004235 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004236 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004237 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004238 Slog.i(TAG, " " + p);
4239 }
4240 }
4241 }
Christopher Tate2982d062011-09-06 20:35:24 -07004242 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004243 } else {
4244 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004245 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004246 }
Dan Egnorefe52642009-06-24 00:16:33 -07004247
Christopher Tate7d562ec2009-06-25 18:03:43 -07004248 // let the observer know that we're running
4249 if (mObserver != null) {
4250 try {
4251 // !!! TODO: get an actual count from the transport after
4252 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004253 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004254 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004255 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004256 mObserver = null;
4257 }
4258 }
Christopher Tate2982d062011-09-06 20:35:24 -07004259 } catch (RemoteException e) {
4260 // Something has gone catastrophically wrong with the transport
4261 Slog.e(TAG, "Error communicating with transport for restore");
4262 executeNextState(RestoreState.FINAL);
4263 return;
4264 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004265
Christopher Tate2982d062011-09-06 20:35:24 -07004266 mStatus = BackupConstants.TRANSPORT_OK;
4267 executeNextState(RestoreState.DOWNLOAD_DATA);
4268 }
4269
4270 void downloadRestoreData() {
4271 // Note that the download phase can be very time consuming, but we're executing
4272 // it inline here on the looper. This is "okay" because it is not calling out to
4273 // third party code; the transport is "trusted," and so we assume it is being a
4274 // good citizen and timing out etc when appropriate.
4275 //
4276 // TODO: when appropriate, move the download off the looper and rearrange the
4277 // error handling around that.
4278 try {
4279 mStatus = mTransport.startRestore(mToken,
4280 mRestorePackages.toArray(new PackageInfo[0]));
4281 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004282 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004283 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004284 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004285 return;
4286 }
Christopher Tate2982d062011-09-06 20:35:24 -07004287 } catch (RemoteException e) {
4288 Slog.e(TAG, "Error communicating with transport for restore");
4289 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4290 mStatus = BackupConstants.TRANSPORT_ERROR;
4291 executeNextState(RestoreState.FINAL);
4292 return;
4293 }
Dan Egnorefe52642009-06-24 00:16:33 -07004294
Christopher Tate2982d062011-09-06 20:35:24 -07004295 // Successful download of the data to be parceled out to the apps, so off we go.
4296 executeNextState(RestoreState.PM_METADATA);
4297 }
4298
4299 void restorePmMetadata() {
4300 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004301 String packageName = mTransport.nextRestorePackage();
4302 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004303 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004304 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004305 mStatus = BackupConstants.TRANSPORT_ERROR;
4306 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004307 return;
4308 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004310 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004311 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004312 mStatus = BackupConstants.TRANSPORT_OK;
4313 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004314 return;
4315 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004317 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004318 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004319 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004320 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004321 return;
4322 }
4323
4324 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004325 PackageInfo omPackage = new PackageInfo();
4326 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4327 mPmAgent = new PackageManagerBackupAgent(
4328 mPackageManager, mAgentPackages);
4329 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004330 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004331 // The PM agent called operationComplete() already, because our invocation
4332 // of it is process-local and therefore synchronous. That means that a
4333 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4334 // proceed with running the queue do we remove that pending message and
4335 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004336
Christopher Tate8c032472009-07-02 14:28:47 -07004337 // Verify that the backup set includes metadata. If not, we can't do
4338 // signature/version verification etc, so we simply do not proceed with
4339 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004340 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004341 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004342 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004343 "Package manager restore metadata missing");
4344 mStatus = BackupConstants.TRANSPORT_ERROR;
4345 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4346 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004347 return;
4348 }
Christopher Tate2982d062011-09-06 20:35:24 -07004349 } catch (RemoteException e) {
4350 Slog.e(TAG, "Error communicating with transport for restore");
4351 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4352 mStatus = BackupConstants.TRANSPORT_ERROR;
4353 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4354 executeNextState(RestoreState.FINAL);
4355 return;
4356 }
Christopher Tate8c032472009-07-02 14:28:47 -07004357
Christopher Tate2982d062011-09-06 20:35:24 -07004358 // Metadata is intact, so we can now run the restore queue. If we get here,
4359 // we have already enqueued the necessary next-step message on the looper.
4360 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004361
Christopher Tate2982d062011-09-06 20:35:24 -07004362 void restoreNextAgent() {
4363 try {
4364 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004365
Christopher Tate2982d062011-09-06 20:35:24 -07004366 if (packageName == null) {
4367 Slog.e(TAG, "Error getting next restore package");
4368 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4369 executeNextState(RestoreState.FINAL);
4370 return;
4371 } else if (packageName.equals("")) {
4372 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4373 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4374 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4375 executeNextState(RestoreState.FINAL);
4376 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004377 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004378
4379 if (mObserver != null) {
4380 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004381 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004382 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004383 Slog.d(TAG, "Restore observer died in onUpdate");
4384 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004385 }
4386 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004387
Christopher Tate2982d062011-09-06 20:35:24 -07004388 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4389 if (metaInfo == null) {
4390 Slog.e(TAG, "Missing metadata for " + packageName);
4391 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4392 "Package metadata missing");
4393 executeNextState(RestoreState.RUNNING_QUEUE);
4394 return;
Christopher Tate84725812010-02-04 15:52:40 -08004395 }
4396
Christopher Tate2982d062011-09-06 20:35:24 -07004397 PackageInfo packageInfo;
4398 try {
4399 int flags = PackageManager.GET_SIGNATURES;
4400 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4401 } catch (NameNotFoundException e) {
4402 Slog.e(TAG, "Invalid package restoring data", e);
4403 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4404 "Package missing on device");
4405 executeNextState(RestoreState.RUNNING_QUEUE);
4406 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004407 }
4408
Christopher Tatee7287a02012-09-07 18:32:12 -07004409 if (packageInfo.applicationInfo.backupAgentName == null
4410 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4411 if (DEBUG) {
4412 Slog.i(TAG, "Data exists for package " + packageName
4413 + " but app has no agent; skipping");
4414 }
4415 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4416 "Package has no agent");
4417 executeNextState(RestoreState.RUNNING_QUEUE);
4418 return;
4419 }
4420
Christopher Tate2982d062011-09-06 20:35:24 -07004421 if (metaInfo.versionCode > packageInfo.versionCode) {
4422 // Data is from a "newer" version of the app than we have currently
4423 // installed. If the app has not declared that it is prepared to
4424 // handle this case, we do not attempt the restore.
4425 if ((packageInfo.applicationInfo.flags
4426 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4427 String message = "Version " + metaInfo.versionCode
4428 + " > installed version " + packageInfo.versionCode;
4429 Slog.w(TAG, "Package " + packageName + ": " + message);
4430 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4431 packageName, message);
4432 executeNextState(RestoreState.RUNNING_QUEUE);
4433 return;
4434 } else {
4435 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4436 + " > installed " + packageInfo.versionCode
4437 + " but restoreAnyVersion");
4438 }
4439 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004440
Christopher Tate2982d062011-09-06 20:35:24 -07004441 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4442 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4443 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4444 "Signature mismatch");
4445 executeNextState(RestoreState.RUNNING_QUEUE);
4446 return;
4447 }
4448
4449 if (DEBUG) Slog.v(TAG, "Package " + packageName
4450 + " restore version [" + metaInfo.versionCode
4451 + "] is compatible with installed version ["
4452 + packageInfo.versionCode + "]");
4453
4454 // Then set up and bind the agent
4455 IBackupAgent agent = bindToAgentSynchronous(
4456 packageInfo.applicationInfo,
4457 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4458 if (agent == null) {
4459 Slog.w(TAG, "Can't find backup agent for " + packageName);
4460 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4461 "Restore agent missing");
4462 executeNextState(RestoreState.RUNNING_QUEUE);
4463 return;
4464 }
4465
4466 // And then finally start the restore on this agent
4467 try {
4468 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4469 ++mCount;
4470 } catch (Exception e) {
4471 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4472 agentErrorCleanup();
4473 executeNextState(RestoreState.RUNNING_QUEUE);
4474 }
4475 } catch (RemoteException e) {
4476 Slog.e(TAG, "Unable to fetch restore data from transport");
4477 mStatus = BackupConstants.TRANSPORT_ERROR;
4478 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004479 }
4480 }
4481
Christopher Tate2982d062011-09-06 20:35:24 -07004482 void finalizeRestore() {
4483 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4484
4485 try {
4486 mTransport.finishRestore();
4487 } catch (RemoteException e) {
4488 Slog.e(TAG, "Error finishing restore", e);
4489 }
4490
4491 if (mObserver != null) {
4492 try {
4493 mObserver.restoreFinished(mStatus);
4494 } catch (RemoteException e) {
4495 Slog.d(TAG, "Restore observer died at restoreFinished");
4496 }
4497 }
4498
4499 // If this was a restoreAll operation, record that this was our
4500 // ancestral dataset, as well as the set of apps that are possibly
4501 // restoreable from the dataset
4502 if (mTargetPackage == null && mPmAgent != null) {
4503 mAncestralPackages = mPmAgent.getRestoredPackages();
4504 mAncestralToken = mToken;
4505 writeRestoreTokens();
4506 }
4507
4508 // We must under all circumstances tell the Package Manager to
4509 // proceed with install notifications if it's waiting for us.
4510 if (mPmToken > 0) {
4511 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4512 try {
4513 mPackageManagerBinder.finishPackageInstall(mPmToken);
4514 } catch (RemoteException e) { /* can't happen */ }
4515 }
4516
4517 // Furthermore we need to reset the session timeout clock
4518 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4519 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4520 TIMEOUT_RESTORE_INTERVAL);
4521
4522 // done; we can finally release the wakelock
4523 Slog.i(TAG, "Restore complete.");
4524 mWakelock.release();
4525 }
4526
4527 // Call asynchronously into the app, passing it the restore data. The next step
4528 // after this is always a callback, either operationComplete() or handleTimeout().
4529 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004530 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004531 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004532 final String packageName = app.packageName;
4533
Christopher Tate2982d062011-09-06 20:35:24 -07004534 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004535
Christopher Tatec7b31e32009-06-10 15:49:30 -07004536 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004537 mBackupDataName = new File(mDataDir, packageName + ".restore");
4538 mNewStateName = new File(mStateDir, packageName + ".new");
4539 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004540
Christopher Tate4a627c72011-04-01 14:43:32 -07004541 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004542 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004543 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004544 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004545 ParcelFileDescriptor.MODE_READ_WRITE |
4546 ParcelFileDescriptor.MODE_CREATE |
4547 ParcelFileDescriptor.MODE_TRUNCATE);
4548
Christopher Tate2982d062011-09-06 20:35:24 -07004549 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004550 // Transport-level failure, so we wind everything up and
4551 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004552 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004553 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004554 mBackupData.close();
4555 mBackupDataName.delete();
4556 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004557 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004558 }
4559
4560 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004561 mBackupData.close();
4562 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004563 ParcelFileDescriptor.MODE_READ_ONLY);
4564
Christopher Tate2982d062011-09-06 20:35:24 -07004565 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004566 ParcelFileDescriptor.MODE_READ_WRITE |
4567 ParcelFileDescriptor.MODE_CREATE |
4568 ParcelFileDescriptor.MODE_TRUNCATE);
4569
Christopher Tate44a27902010-01-27 17:15:49 -08004570 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004571 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4572 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004573 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004574 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004575 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004576 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004577
Christopher Tate2982d062011-09-06 20:35:24 -07004578 // After a restore failure we go back to running the queue. If there
4579 // are no more packages to be restored that will be handled by the
4580 // next step.
4581 executeNextState(RestoreState.RUNNING_QUEUE);
4582 }
4583 }
Chris Tate249345b2010-10-29 12:57:04 -07004584
Christopher Tate2982d062011-09-06 20:35:24 -07004585 void agentErrorCleanup() {
4586 // If the agent fails restore, it might have put the app's data
4587 // into an incoherent state. For consistency we wipe its data
4588 // again in this case before continuing with normal teardown
4589 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4590 agentCleanup();
4591 }
4592
4593 void agentCleanup() {
4594 mBackupDataName.delete();
4595 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4596 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4597 mBackupData = mNewState = null;
4598
4599 // if everything went okay, remember the recorded state now
4600 //
4601 // !!! TODO: the restored data should be migrated on the server
4602 // side into the current dataset. In that case the new state file
4603 // we just created would reflect the data already extant in the
4604 // backend, so there'd be nothing more to do. Until that happens,
4605 // however, we need to make sure that we record the data to the
4606 // current backend dataset. (Yes, this means shipping the data over
4607 // the wire in both directions. That's bad, but consistency comes
4608 // first, then efficiency.) Once we introduce server-side data
4609 // migration to the newly-restored device's dataset, we will change
4610 // the following from a discard of the newly-written state to the
4611 // "correct" operation of renaming into the canonical state blob.
4612 mNewStateName.delete(); // TODO: remove; see above comment
4613 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4614
4615 // If this wasn't the PM pseudopackage, tear down the agent side
4616 if (mCurrentPackage.applicationInfo != null) {
4617 // unbind and tidy up even on timeout or failure
4618 try {
4619 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4620
4621 // The agent was probably running with a stub Application object,
4622 // which isn't a valid run mode for the main app logic. Shut
4623 // down the app so that next time it's launched, it gets the
4624 // usual full initialization. Note that this is only done for
4625 // full-system restores: when a single app has requested a restore,
4626 // it is explicitly not killed following that operation.
4627 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4628 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4629 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4630 + mCurrentPackage.applicationInfo.processName);
4631 mActivityManager.killApplicationProcess(
4632 mCurrentPackage.applicationInfo.processName,
4633 mCurrentPackage.applicationInfo.uid);
4634 }
4635 } catch (RemoteException e) {
4636 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004637 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004638 }
Christopher Tate2982d062011-09-06 20:35:24 -07004639
4640 // The caller is responsible for reestablishing the state machine; our
4641 // responsibility here is to clear the decks for whatever comes next.
4642 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4643 synchronized (mCurrentOpLock) {
4644 mCurrentOperations.clear();
4645 }
4646 }
4647
4648 // A call to agent.doRestore() has been positively acknowledged as complete
4649 @Override
4650 public void operationComplete() {
4651 int size = (int) mBackupDataName.length();
4652 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4653 // Just go back to running the restore queue
4654 agentCleanup();
4655
4656 executeNextState(RestoreState.RUNNING_QUEUE);
4657 }
4658
4659 // A call to agent.doRestore() has timed out
4660 @Override
4661 public void handleTimeout() {
4662 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4663 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4664 mCurrentPackage.packageName, "restore timeout");
4665 // Handle like an agent that threw on invocation: wipe it and go on to the next
4666 agentErrorCleanup();
4667 executeNextState(RestoreState.RUNNING_QUEUE);
4668 }
4669
4670 void executeNextState(RestoreState nextState) {
4671 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4672 + this + " nextState=" + nextState);
4673 mCurrentState = nextState;
4674 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4675 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004676 }
4677 }
4678
Christopher Tate44a27902010-01-27 17:15:49 -08004679 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004680 IBackupTransport mTransport;
4681 PackageInfo mPackage;
4682
Christopher Tate44a27902010-01-27 17:15:49 -08004683 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004684 mTransport = transport;
4685 mPackage = packageInfo;
4686 }
4687
Christopher Tateee0e78a2009-07-02 11:17:03 -07004688 public void run() {
4689 try {
4690 // Clear the on-device backup state to ensure a full backup next time
4691 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4692 File stateFile = new File(stateDir, mPackage.packageName);
4693 stateFile.delete();
4694
4695 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004696 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004697 mTransport.clearBackupData(mPackage);
4698 } catch (RemoteException e) {
4699 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004700 } catch (Exception e) {
4701 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004702 } finally {
4703 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004704 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004705 mTransport.finishBackup();
4706 } catch (RemoteException e) {
4707 // can't happen; the transport is local
4708 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004709
4710 // Last but not least, release the cpu
4711 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004712 }
4713 }
4714 }
4715
Christopher Tate44a27902010-01-27 17:15:49 -08004716 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004717 HashSet<String> mQueue;
4718
Christopher Tate44a27902010-01-27 17:15:49 -08004719 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004720 mQueue = transportNames;
4721 }
4722
Christopher Tate4cc86e12009-09-21 19:36:51 -07004723 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004724 try {
4725 for (String transportName : mQueue) {
4726 IBackupTransport transport = getTransport(transportName);
4727 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004728 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004729 continue;
4730 }
4731
Joe Onorato8a9b2202010-02-26 18:56:32 -08004732 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004733 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004734 long startRealtime = SystemClock.elapsedRealtime();
4735 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004736
Christopher Tate4cc86e12009-09-21 19:36:51 -07004737 if (status == BackupConstants.TRANSPORT_OK) {
4738 status = transport.finishBackup();
4739 }
4740
4741 // Okay, the wipe really happened. Clean up our local bookkeeping.
4742 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004743 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004744 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004745 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004746 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004747 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004748 synchronized (mQueueLock) {
4749 recordInitPendingLocked(false, transportName);
4750 }
Dan Egnor726247c2009-09-29 19:12:31 -07004751 } else {
4752 // If this didn't work, requeue this one and try again
4753 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004754 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004755 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004756 synchronized (mQueueLock) {
4757 recordInitPendingLocked(true, transportName);
4758 }
4759 // do this via another alarm to make sure of the wakelock states
4760 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004761 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004762 + transportName + " resched in " + delay);
4763 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4764 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004765 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004766 }
4767 } catch (RemoteException e) {
4768 // can't happen; the transports are local
4769 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004770 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004771 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004772 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004773 mWakelock.release();
4774 }
4775 }
4776 }
4777
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004778 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004779 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004780 dataChangedImpl(packageName, targets);
4781 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004782
Christopher Tatea3d55342012-03-27 13:16:18 -07004783 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004784 // Record that we need a backup pass for the caller. Since multiple callers
4785 // may share a uid, we need to note all candidates within that uid and schedule
4786 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004787 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004788
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004789 if (targets == null) {
4790 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4791 + " uid=" + Binder.getCallingUid());
4792 return;
4793 }
4794
4795 synchronized (mQueueLock) {
4796 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004797 if (targets.contains(packageName)) {
4798 // Add the caller to the set of pending backups. If there is
4799 // one already there, then overwrite it, but no harm done.
4800 BackupRequest req = new BackupRequest(packageName);
4801 if (mPendingBackups.put(packageName, req) == null) {
4802 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004803
Christopher Tatea3d55342012-03-27 13:16:18 -07004804 // Journal this request in case of crash. The put()
4805 // operation returned null when this package was not already
4806 // in the set; we want to avoid touching the disk redundantly.
4807 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004808
Christopher Tatea3d55342012-03-27 13:16:18 -07004809 if (MORE_DEBUG) {
4810 int numKeys = mPendingBackups.size();
4811 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4812 for (BackupRequest b : mPendingBackups.values()) {
4813 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004814 }
4815 }
4816 }
4817 }
4818 }
4819 }
4820
4821 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004822 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004823 // If the caller does not hold the BACKUP permission, it can only request a
4824 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004825 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004826 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004827 synchronized (mBackupParticipants) {
4828 return mBackupParticipants.get(Binder.getCallingUid());
4829 }
4830 }
4831
4832 // a caller with full permission can ask to back up any participating app
4833 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004834 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004835 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004836 int N = mBackupParticipants.size();
4837 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004838 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004839 if (s != null) {
4840 targets.addAll(s);
4841 }
4842 }
4843 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004844 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004845 }
Christopher Tate46758122009-05-06 11:22:00 -07004846
Christopher Tatecde87f42009-06-12 12:55:53 -07004847 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004848 RandomAccessFile out = null;
4849 try {
4850 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4851 out = new RandomAccessFile(mJournal, "rws");
4852 out.seek(out.length());
4853 out.writeUTF(str);
4854 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004855 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004856 mJournal = null;
4857 } finally {
4858 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004859 }
4860 }
4861
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004862 // ----- IBackupManager binder interface -----
4863
4864 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004865 final int callingUserHandle = UserHandle.getCallingUserId();
4866 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004867 // App is running under a non-owner user profile. For now, we do not back
4868 // up data from secondary user profiles.
4869 // TODO: backups for all user profiles.
4870 if (MORE_DEBUG) {
4871 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4872 + callingUserHandle);
4873 }
4874 return;
4875 }
4876
Christopher Tatea3d55342012-03-27 13:16:18 -07004877 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004878 if (targets == null) {
4879 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4880 + " uid=" + Binder.getCallingUid());
4881 return;
4882 }
4883
4884 mBackupHandler.post(new Runnable() {
4885 public void run() {
4886 dataChangedImpl(packageName, targets);
4887 }
4888 });
4889 }
4890
Christopher Tateee0e78a2009-07-02 11:17:03 -07004891 // Clear the given package's backup data from the current transport
4892 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004893 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004894 PackageInfo info;
4895 try {
4896 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4897 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004898 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004899 return;
4900 }
4901
4902 // If the caller does not hold the BACKUP permission, it can only request a
4903 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004904 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004905 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004906 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4907 apps = mBackupParticipants.get(Binder.getCallingUid());
4908 } else {
4909 // a caller with full permission can ask to back up any participating app
4910 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004911 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004912 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004913 int N = mBackupParticipants.size();
4914 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004915 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004916 if (s != null) {
4917 apps.addAll(s);
4918 }
4919 }
4920 }
4921
Christopher Tatea3d55342012-03-27 13:16:18 -07004922 // Is the given app an available participant?
4923 if (apps.contains(packageName)) {
4924 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4925 // found it; fire off the clear request
4926 synchronized (mQueueLock) {
4927 long oldId = Binder.clearCallingIdentity();
4928 mWakelock.acquire();
4929 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4930 new ClearParams(getTransport(mCurrentTransport), info));
4931 mBackupHandler.sendMessage(msg);
4932 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004933 }
4934 }
4935 }
4936
Christopher Tateace7f092009-06-15 18:07:25 -07004937 // Run a backup pass immediately for any applications that have declared
4938 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004939 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004940 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004941
Joe Onorato8a9b2202010-02-26 18:56:32 -08004942 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004943 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004944 // Because the alarms we are using can jitter, and we want an *immediate*
4945 // backup pass to happen, we restart the timer beginning with "next time,"
4946 // then manually fire the backup trigger intent ourselves.
4947 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004948 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004949 mRunBackupIntent.send();
4950 } catch (PendingIntent.CanceledException e) {
4951 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004952 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004953 }
Christopher Tate46758122009-05-06 11:22:00 -07004954 }
4955 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004956
Christopher Tated2c0cd42011-09-15 15:51:29 -07004957 boolean deviceIsProvisioned() {
4958 final ContentResolver resolver = mContext.getContentResolver();
4959 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4960 }
4961
Christopher Tate4a627c72011-04-01 14:43:32 -07004962 // Run a *full* backup pass for the given package, writing the resulting data stream
4963 // to the supplied file descriptor. This method is synchronous and does not return
4964 // to the caller until the backup has been completed.
4965 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004966 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004967 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4968
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004969 final int callingUserHandle = UserHandle.getCallingUserId();
4970 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004971 throw new IllegalStateException("Backup supported only for the device owner");
4972 }
4973
Christopher Tate4a627c72011-04-01 14:43:32 -07004974 // Validate
4975 if (!doAllApps) {
4976 if (!includeShared) {
4977 // If we're backing up shared data (sdcard or equivalent), then we can run
4978 // without any supplied app names. Otherwise, we'd be doing no work, so
4979 // report the error.
4980 if (pkgList == null || pkgList.length == 0) {
4981 throw new IllegalArgumentException(
4982 "Backup requested but neither shared nor any apps named");
4983 }
4984 }
4985 }
4986
Christopher Tate4a627c72011-04-01 14:43:32 -07004987 long oldId = Binder.clearCallingIdentity();
4988 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004989 // Doesn't make sense to do a full backup prior to setup
4990 if (!deviceIsProvisioned()) {
4991 Slog.i(TAG, "Full backup not supported before setup");
4992 return;
4993 }
4994
4995 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4996 + " shared=" + includeShared + " all=" + doAllApps
4997 + " pkgs=" + pkgList);
4998 Slog.i(TAG, "Beginning full backup...");
4999
Christopher Tate4a627c72011-04-01 14:43:32 -07005000 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005001 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005002 final int token = generateToken();
5003 synchronized (mFullConfirmations) {
5004 mFullConfirmations.put(token, params);
5005 }
5006
Christopher Tate75a99702011-05-18 16:28:19 -07005007 // start up the confirmation UI
5008 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5009 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5010 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005011 mFullConfirmations.delete(token);
5012 return;
5013 }
Christopher Tate75a99702011-05-18 16:28:19 -07005014
5015 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005016 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5017
5018 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005019 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005020
5021 // wait for the backup to be performed
5022 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5023 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005024 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005025 try {
5026 fd.close();
5027 } catch (IOException e) {
5028 // just eat it
5029 }
Christopher Tate75a99702011-05-18 16:28:19 -07005030 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005031 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005032 }
Christopher Tate75a99702011-05-18 16:28:19 -07005033 }
5034
5035 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005036 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005037
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005038 final int callingUserHandle = UserHandle.getCallingUserId();
5039 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005040 throw new IllegalStateException("Restore supported only for the device owner");
5041 }
5042
Christopher Tate75a99702011-05-18 16:28:19 -07005043 long oldId = Binder.clearCallingIdentity();
5044
5045 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005046 // Check whether the device has been provisioned -- we don't handle
5047 // full restores prior to completing the setup process.
5048 if (!deviceIsProvisioned()) {
5049 Slog.i(TAG, "Full restore not permitted before setup");
5050 return;
5051 }
5052
5053 Slog.i(TAG, "Beginning full restore...");
5054
Christopher Tate75a99702011-05-18 16:28:19 -07005055 FullRestoreParams params = new FullRestoreParams(fd);
5056 final int token = generateToken();
5057 synchronized (mFullConfirmations) {
5058 mFullConfirmations.put(token, params);
5059 }
5060
5061 // start up the confirmation UI
5062 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5063 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5064 Slog.e(TAG, "Unable to launch full restore confirmation");
5065 mFullConfirmations.delete(token);
5066 return;
5067 }
5068
5069 // make sure the screen is lit for the user interaction
5070 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5071
5072 // start the confirmation countdown
5073 startConfirmationTimeout(token, params);
5074
5075 // wait for the restore to be performed
5076 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5077 waitForCompletion(params);
5078 } finally {
5079 try {
5080 fd.close();
5081 } catch (IOException e) {
5082 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5083 }
5084 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005085 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005086 }
5087 }
5088
5089 boolean startConfirmationUi(int token, String action) {
5090 try {
5091 Intent confIntent = new Intent(action);
5092 confIntent.setClassName("com.android.backupconfirm",
5093 "com.android.backupconfirm.BackupRestoreConfirmation");
5094 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5095 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5096 mContext.startActivity(confIntent);
5097 } catch (ActivityNotFoundException e) {
5098 return false;
5099 }
5100 return true;
5101 }
5102
5103 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005104 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005105 + TIMEOUT_FULL_CONFIRMATION + " millis");
5106 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5107 token, 0, params);
5108 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005109 }
5110
5111 void waitForCompletion(FullParams params) {
5112 synchronized (params.latch) {
5113 while (params.latch.get() == false) {
5114 try {
5115 params.latch.wait();
5116 } catch (InterruptedException e) { /* never interrupted */ }
5117 }
5118 }
5119 }
5120
5121 void signalFullBackupRestoreCompletion(FullParams params) {
5122 synchronized (params.latch) {
5123 params.latch.set(true);
5124 params.latch.notifyAll();
5125 }
5126 }
5127
5128 // Confirm that the previously-requested full backup/restore operation can proceed. This
5129 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005130 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005131 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005132 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005133 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5134 + " allow=" + allow);
5135
5136 // TODO: possibly require not just this signature-only permission, but even
5137 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005138 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005139
5140 long oldId = Binder.clearCallingIdentity();
5141 try {
5142
5143 FullParams params;
5144 synchronized (mFullConfirmations) {
5145 params = mFullConfirmations.get(token);
5146 if (params != null) {
5147 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5148 mFullConfirmations.delete(token);
5149
5150 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005151 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005152 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005153 : MSG_RUN_FULL_RESTORE;
5154
Christopher Tate728a1c42011-07-28 18:03:03 -07005155 params.observer = observer;
5156 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005157
5158 boolean isEncrypted;
5159 try {
5160 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5161 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5162 } catch (RemoteException e) {
5163 // couldn't contact the mount service; fail "safe" and assume encryption
5164 Slog.e(TAG, "Unable to contact mount service!");
5165 isEncrypted = true;
5166 }
5167 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005168
Christopher Tate75a99702011-05-18 16:28:19 -07005169 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005170 mWakelock.acquire();
5171 Message msg = mBackupHandler.obtainMessage(verb, params);
5172 mBackupHandler.sendMessage(msg);
5173 } else {
5174 Slog.w(TAG, "User rejected full backup/restore operation");
5175 // indicate completion without having actually transferred any data
5176 signalFullBackupRestoreCompletion(params);
5177 }
5178 } else {
5179 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5180 }
5181 }
5182 } finally {
5183 Binder.restoreCallingIdentity(oldId);
5184 }
5185 }
5186
Christopher Tate8031a3d2009-07-06 16:36:05 -07005187 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005188 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005189 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005190 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005191
Joe Onorato8a9b2202010-02-26 18:56:32 -08005192 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005193
Christopher Tate6ef58a12009-06-29 14:56:28 -07005194 boolean wasEnabled = mEnabled;
5195 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005196 Settings.Secure.putInt(mContext.getContentResolver(),
5197 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005198 mEnabled = enable;
5199 }
5200
Christopher Tate49401dd2009-07-01 12:34:29 -07005201 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005202 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005203 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005204 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005205 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005206 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005207 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005208
Christopher Tateb6787f22009-07-02 17:40:45 -07005209 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005210
5211 // This also constitutes an opt-out, so we wipe any data for
5212 // this device from the backend. We start that process with
5213 // an alarm in order to guarantee wakelock states.
5214 if (wasEnabled && mProvisioned) {
5215 // NOTE: we currently flush every registered transport, not just
5216 // the currently-active one.
5217 HashSet<String> allTransports;
5218 synchronized (mTransports) {
5219 allTransports = new HashSet<String>(mTransports.keySet());
5220 }
5221 // build the set of transports for which we are posting an init
5222 for (String transport : allTransports) {
5223 recordInitPendingLocked(true, transport);
5224 }
5225 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5226 mRunInitIntent);
5227 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005228 }
5229 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005230 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005231
Christopher Tatecce9da52010-02-03 15:11:15 -08005232 // Enable/disable automatic restore of app data at install time
5233 public void setAutoRestore(boolean doAutoRestore) {
5234 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005235 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005236
Joe Onorato8a9b2202010-02-26 18:56:32 -08005237 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005238
5239 synchronized (this) {
5240 Settings.Secure.putInt(mContext.getContentResolver(),
5241 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5242 mAutoRestore = doAutoRestore;
5243 }
5244 }
5245
Christopher Tate8031a3d2009-07-06 16:36:05 -07005246 // Mark the backup service as having been provisioned
5247 public void setBackupProvisioned(boolean available) {
5248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5249 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005250 /*
5251 * This is now a no-op; provisioning is simply the device's own setup state.
5252 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005253 }
5254
5255 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005256 // We used to use setInexactRepeating(), but that may be linked to
5257 // backups running at :00 more often than not, creating load spikes.
5258 // Schedule at an exact time for now, and also add a bit of "fuzz".
5259
5260 Random random = new Random();
5261 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5262 random.nextInt(FUZZ_MILLIS);
5263 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5264 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005265 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005266 }
5267
Christopher Tate6ef58a12009-06-29 14:56:28 -07005268 // Report whether the backup mechanism is currently enabled
5269 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005270 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005271 return mEnabled; // no need to synchronize just to read it
5272 }
5273
Christopher Tate91717492009-06-26 21:07:13 -07005274 // Report the name of the currently active transport
5275 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005277 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005278 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005279 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005280 }
5281
Christopher Tate91717492009-06-26 21:07:13 -07005282 // Report all known, available backup transports
5283 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005284 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005285
Christopher Tate91717492009-06-26 21:07:13 -07005286 String[] list = null;
5287 ArrayList<String> known = new ArrayList<String>();
5288 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5289 if (entry.getValue() != null) {
5290 known.add(entry.getKey());
5291 }
5292 }
5293
5294 if (known.size() > 0) {
5295 list = new String[known.size()];
5296 known.toArray(list);
5297 }
5298 return list;
5299 }
5300
5301 // Select which transport to use for the next backup operation. If the given
5302 // name is not one of the available transports, no action is taken and the method
5303 // returns null.
5304 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005306
5307 synchronized (mTransports) {
5308 String prevTransport = null;
5309 if (mTransports.get(transport) != null) {
5310 prevTransport = mCurrentTransport;
5311 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005312 Settings.Secure.putString(mContext.getContentResolver(),
5313 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005314 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005315 + " returning " + prevTransport);
5316 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005317 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005318 }
5319 return prevTransport;
5320 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005321 }
5322
Christopher Tatef5e1c292010-12-08 18:40:26 -08005323 // Supply the configuration Intent for the given transport. If the name is not one
5324 // of the available transports, or if the transport does not supply any configuration
5325 // UI, the method returns null.
5326 public Intent getConfigurationIntent(String transportName) {
5327 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5328 "getConfigurationIntent");
5329
5330 synchronized (mTransports) {
5331 final IBackupTransport transport = mTransports.get(transportName);
5332 if (transport != null) {
5333 try {
5334 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005335 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005336 + intent);
5337 return intent;
5338 } catch (RemoteException e) {
5339 /* fall through to return null */
5340 }
5341 }
5342 }
5343
5344 return null;
5345 }
5346
5347 // Supply the configuration summary string for the given transport. If the name is
5348 // not one of the available transports, or if the transport does not supply any
5349 // summary / destination string, the method can return null.
5350 //
5351 // This string is used VERBATIM as the summary text of the relevant Settings item!
5352 public String getDestinationString(String transportName) {
5353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005354 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005355
5356 synchronized (mTransports) {
5357 final IBackupTransport transport = mTransports.get(transportName);
5358 if (transport != null) {
5359 try {
5360 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005361 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005362 return text;
5363 } catch (RemoteException e) {
5364 /* fall through to return null */
5365 }
5366 }
5367 }
5368
5369 return null;
5370 }
5371
Christopher Tate043dadc2009-06-02 16:11:00 -07005372 // Callback: a requested backup agent has been instantiated. This should only
5373 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005374 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005375 synchronized(mAgentConnectLock) {
5376 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005377 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005378 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5379 mConnectedAgent = agent;
5380 mConnecting = false;
5381 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005382 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005383 + " claiming agent connected");
5384 }
5385 mAgentConnectLock.notifyAll();
5386 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005387 }
5388
5389 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5390 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005391 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005392 public void agentDisconnected(String packageName) {
5393 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005394 synchronized(mAgentConnectLock) {
5395 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5396 mConnectedAgent = null;
5397 mConnecting = false;
5398 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005399 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005400 + " claiming agent disconnected");
5401 }
5402 mAgentConnectLock.notifyAll();
5403 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005404 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005405
Christopher Tate1bb69062010-02-19 17:02:12 -08005406 // An application being installed will need a restore pass, then the Package Manager
5407 // will need to be told when the restore is finished.
5408 public void restoreAtInstall(String packageName, int token) {
5409 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005410 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005411 + " attemping install-time restore");
5412 return;
5413 }
5414
5415 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005416 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005417 + " token=" + Integer.toHexString(token));
5418
Christopher Tatef0872722010-02-25 15:22:48 -08005419 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005420 // okay, we're going to attempt a restore of this package from this restore set.
5421 // The eventual message back into the Package Manager to run the post-install
5422 // steps for 'token' will be issued from the restore handling code.
5423
5424 // We can use a synthetic PackageInfo here because:
5425 // 1. We know it's valid, since the Package Manager supplied the name
5426 // 2. Only the packageName field will be used by the restore code
5427 PackageInfo pkg = new PackageInfo();
5428 pkg.packageName = packageName;
5429
5430 mWakelock.acquire();
5431 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5432 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005433 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005434 mBackupHandler.sendMessage(msg);
5435 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005436 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5437 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005438 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005439 try {
5440 mPackageManagerBinder.finishPackageInstall(token);
5441 } catch (RemoteException e) { /* can't happen */ }
5442 }
5443 }
5444
Christopher Tate8c850b72009-06-07 19:33:20 -07005445 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005446 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5447 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5448 + " transport=" + transport);
5449
5450 boolean needPermission = true;
5451 if (transport == null) {
5452 transport = mCurrentTransport;
5453
5454 if (packageName != null) {
5455 PackageInfo app = null;
5456 try {
5457 app = mPackageManager.getPackageInfo(packageName, 0);
5458 } catch (NameNotFoundException nnf) {
5459 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5460 throw new IllegalArgumentException("Package " + packageName + " not found");
5461 }
5462
5463 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5464 // So: using the current active transport, and the caller has asked
5465 // that its own package will be restored. In this narrow use case
5466 // we do not require the caller to hold the permission.
5467 needPermission = false;
5468 }
5469 }
5470 }
5471
5472 if (needPermission) {
5473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5474 "beginRestoreSession");
5475 } else {
5476 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5477 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005478
5479 synchronized(this) {
5480 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005481 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005482 return null;
5483 }
Chris Tate44ab8452010-11-16 15:10:49 -08005484 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005485 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005486 }
5487 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005488 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005489
Christopher Tate73a3cb32010-12-13 18:27:26 -08005490 void clearRestoreSession(ActiveRestoreSession currentSession) {
5491 synchronized(this) {
5492 if (currentSession != mActiveRestoreSession) {
5493 Slog.e(TAG, "ending non-current restore session");
5494 } else {
5495 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5496 mActiveRestoreSession = null;
5497 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5498 }
5499 }
5500 }
5501
Christopher Tate44a27902010-01-27 17:15:49 -08005502 // Note that a currently-active backup agent has notified us that it has
5503 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005504 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005505 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005506 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5507 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005508 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005509 op = mCurrentOperations.get(token);
5510 if (op != null) {
5511 op.state = OP_ACKNOWLEDGED;
5512 }
Christopher Tate44a27902010-01-27 17:15:49 -08005513 mCurrentOpLock.notifyAll();
5514 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005515
5516 // The completion callback, if any, is invoked on the handler
5517 if (op != null && op.callback != null) {
5518 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5519 mBackupHandler.sendMessage(msg);
5520 }
Christopher Tate44a27902010-01-27 17:15:49 -08005521 }
5522
Christopher Tate9b3905c2009-06-08 15:24:01 -07005523 // ----- Restore session -----
5524
Christopher Tate80202c82010-01-25 19:37:47 -08005525 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005526 private static final String TAG = "RestoreSession";
5527
Chris Tate44ab8452010-11-16 15:10:49 -08005528 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005529 private IBackupTransport mRestoreTransport = null;
5530 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005531 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005532
Chris Tate44ab8452010-11-16 15:10:49 -08005533 ActiveRestoreSession(String packageName, String transport) {
5534 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005535 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005536 }
5537
5538 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005539 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005541 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005542 if (observer == null) {
5543 throw new IllegalArgumentException("Observer must not be null");
5544 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005545
Christopher Tate73a3cb32010-12-13 18:27:26 -08005546 if (mEnded) {
5547 throw new IllegalStateException("Restore session already ended");
5548 }
5549
Christopher Tate1bb69062010-02-19 17:02:12 -08005550 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005551 try {
Christopher Tate43383042009-07-13 15:17:13 -07005552 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005553 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005554 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005555 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005556 // spin off the transport request to our service thread
5557 mWakelock.acquire();
5558 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5559 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5560 mBackupHandler.sendMessage(msg);
5561 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005562 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005563 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005564 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005565 } finally {
5566 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005567 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005568 }
5569
Christopher Tate84725812010-02-04 15:52:40 -08005570 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5572 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005573
Chris Tate44ab8452010-11-16 15:10:49 -08005574 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005575 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005576
Christopher Tate73a3cb32010-12-13 18:27:26 -08005577 if (mEnded) {
5578 throw new IllegalStateException("Restore session already ended");
5579 }
5580
Dan Egnor0084da52009-07-29 12:57:16 -07005581 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005582 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5583 return -1;
5584 }
5585
5586 if (mPackageName != null) {
5587 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005588 return -1;
5589 }
5590
Christopher Tate21ab6a52009-09-24 18:01:46 -07005591 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005592 for (int i = 0; i < mRestoreSets.length; i++) {
5593 if (token == mRestoreSets[i].token) {
5594 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005595 mWakelock.acquire();
5596 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005597 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005598 mBackupHandler.sendMessage(msg);
5599 Binder.restoreCallingIdentity(oldId);
5600 return 0;
5601 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005602 }
5603 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005604
Joe Onorato8a9b2202010-02-26 18:56:32 -08005605 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005606 return -1;
5607 }
5608
Christopher Tate284f1bb2011-07-07 14:31:18 -07005609 public synchronized int restoreSome(long token, IRestoreObserver observer,
5610 String[] packages) {
5611 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5612 "performRestore");
5613
5614 if (DEBUG) {
5615 StringBuilder b = new StringBuilder(128);
5616 b.append("restoreSome token=");
5617 b.append(Long.toHexString(token));
5618 b.append(" observer=");
5619 b.append(observer.toString());
5620 b.append(" packages=");
5621 if (packages == null) {
5622 b.append("null");
5623 } else {
5624 b.append('{');
5625 boolean first = true;
5626 for (String s : packages) {
5627 if (!first) {
5628 b.append(", ");
5629 } else first = false;
5630 b.append(s);
5631 }
5632 b.append('}');
5633 }
5634 Slog.d(TAG, b.toString());
5635 }
5636
5637 if (mEnded) {
5638 throw new IllegalStateException("Restore session already ended");
5639 }
5640
5641 if (mRestoreTransport == null || mRestoreSets == null) {
5642 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5643 return -1;
5644 }
5645
5646 if (mPackageName != null) {
5647 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5648 return -1;
5649 }
5650
5651 synchronized (mQueueLock) {
5652 for (int i = 0; i < mRestoreSets.length; i++) {
5653 if (token == mRestoreSets[i].token) {
5654 long oldId = Binder.clearCallingIdentity();
5655 mWakelock.acquire();
5656 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5657 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5658 packages, true);
5659 mBackupHandler.sendMessage(msg);
5660 Binder.restoreCallingIdentity(oldId);
5661 return 0;
5662 }
5663 }
5664 }
5665
5666 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5667 return -1;
5668 }
5669
Christopher Tate84725812010-02-04 15:52:40 -08005670 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005671 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005672
Christopher Tate73a3cb32010-12-13 18:27:26 -08005673 if (mEnded) {
5674 throw new IllegalStateException("Restore session already ended");
5675 }
5676
Chris Tate44ab8452010-11-16 15:10:49 -08005677 if (mPackageName != null) {
5678 if (! mPackageName.equals(packageName)) {
5679 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5680 + " on session for package " + mPackageName);
5681 return -1;
5682 }
5683 }
5684
Christopher Tate84725812010-02-04 15:52:40 -08005685 PackageInfo app = null;
5686 try {
5687 app = mPackageManager.getPackageInfo(packageName, 0);
5688 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005689 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005690 return -1;
5691 }
5692
5693 // If the caller is not privileged and is not coming from the target
5694 // app's uid, throw a permission exception back to the caller.
5695 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5696 Binder.getCallingPid(), Binder.getCallingUid());
5697 if ((perm == PackageManager.PERMISSION_DENIED) &&
5698 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005699 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005700 + " or calling uid=" + Binder.getCallingUid());
5701 throw new SecurityException("No permission to restore other packages");
5702 }
5703
Christopher Tate7d411a32010-02-26 11:27:08 -08005704 // If the package has no backup agent, we obviously cannot proceed
5705 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005706 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005707 return -1;
5708 }
5709
Christopher Tate84725812010-02-04 15:52:40 -08005710 // So far so good; we're allowed to try to restore this package. Now
5711 // check whether there is data for it in the current dataset, falling back
5712 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005713 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005714
5715 // If we didn't come up with a place to look -- no ancestral dataset and
5716 // the app has never been backed up from this device -- there's nothing
5717 // to do but return failure.
5718 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005719 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005720 return -1;
5721 }
5722
5723 // Ready to go: enqueue the restore request and claim success
5724 long oldId = Binder.clearCallingIdentity();
5725 mWakelock.acquire();
5726 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005727 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005728 mBackupHandler.sendMessage(msg);
5729 Binder.restoreCallingIdentity(oldId);
5730 return 0;
5731 }
5732
Christopher Tate73a3cb32010-12-13 18:27:26 -08005733 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5734 class EndRestoreRunnable implements Runnable {
5735 BackupManagerService mBackupManager;
5736 ActiveRestoreSession mSession;
5737
5738 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5739 mBackupManager = manager;
5740 mSession = session;
5741 }
5742
5743 public void run() {
5744 // clean up the session's bookkeeping
5745 synchronized (mSession) {
5746 try {
5747 if (mSession.mRestoreTransport != null) {
5748 mSession.mRestoreTransport.finishRestore();
5749 }
5750 } catch (Exception e) {
5751 Slog.e(TAG, "Error in finishRestore", e);
5752 } finally {
5753 mSession.mRestoreTransport = null;
5754 mSession.mEnded = true;
5755 }
5756 }
5757
5758 // clean up the BackupManagerService side of the bookkeeping
5759 // and cancel any pending timeout message
5760 mBackupManager.clearRestoreSession(mSession);
5761 }
5762 }
5763
Dan Egnor0084da52009-07-29 12:57:16 -07005764 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005765 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005766
Christopher Tate73a3cb32010-12-13 18:27:26 -08005767 if (mEnded) {
5768 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005769 }
5770
Christopher Tate73a3cb32010-12-13 18:27:26 -08005771 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005772 }
5773 }
5774
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005775 @Override
5776 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5778
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005779 long identityToken = Binder.clearCallingIdentity();
5780 try {
5781 dumpInternal(pw);
5782 } finally {
5783 Binder.restoreCallingIdentity(identityToken);
5784 }
5785 }
5786
5787 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005788 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005789 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005790 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005791 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005792 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005793 if (mBackupRunning) pw.println("Backup currently running");
5794 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005795 + " (now = " + System.currentTimeMillis() + ')');
5796 pw.println(" next scheduled: " + mNextBackupPass);
5797
Christopher Tate91717492009-06-26 21:07:13 -07005798 pw.println("Available transports:");
5799 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005800 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5801 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005802 IBackupTransport transport = getTransport(t);
5803 File dir = new File(mBaseStateDir, transport.transportDirName());
5804 pw.println(" destination: " + transport.currentDestinationString());
5805 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005806 for (File f : dir.listFiles()) {
5807 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5808 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005809 } catch (Exception e) {
5810 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005811 pw.println(" Error: " + e);
5812 }
Christopher Tate91717492009-06-26 21:07:13 -07005813 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005814
5815 pw.println("Pending init: " + mPendingInits.size());
5816 for (String s : mPendingInits) {
5817 pw.println(" " + s);
5818 }
5819
Christopher Tate6de74ff2012-01-17 15:20:32 -08005820 if (DEBUG_BACKUP_TRACE) {
5821 synchronized (mBackupTrace) {
5822 if (!mBackupTrace.isEmpty()) {
5823 pw.println("Most recent backup trace:");
5824 for (String s : mBackupTrace) {
5825 pw.println(" " + s);
5826 }
5827 }
5828 }
5829 }
5830
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005831 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005832 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005833 for (int i=0; i<N; i++) {
5834 int uid = mBackupParticipants.keyAt(i);
5835 pw.print(" uid: ");
5836 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005837 HashSet<String> participants = mBackupParticipants.valueAt(i);
5838 for (String app: participants) {
5839 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005840 }
5841 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005842
Christopher Tateb49ceb32010-02-08 16:22:24 -08005843 pw.println("Ancestral packages: "
5844 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005845 if (mAncestralPackages != null) {
5846 for (String pkg : mAncestralPackages) {
5847 pw.println(" " + pkg);
5848 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005849 }
5850
Christopher Tate73e02522009-07-15 14:18:26 -07005851 pw.println("Ever backed up: " + mEverStoredApps.size());
5852 for (String pkg : mEverStoredApps) {
5853 pw.println(" " + pkg);
5854 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005855
5856 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005857 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005858 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005859 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005860 }
5861 }
Christopher Tate487529a2009-04-29 14:03:25 -07005862}