blob: 8be0ba8af3e7363f3476b8c843d02514a912bd36 [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;
Christopher Tate32418be2011-10-10 13:51:12 -070070import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080071import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070072import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070073import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080074import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070075import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070076import android.util.StringBuilderPrinter;
77
Jason parksa3cdaa52011-01-13 14:15:43 -060078import com.android.internal.backup.BackupConstants;
79import com.android.internal.backup.IBackupTransport;
80import com.android.internal.backup.LocalTransport;
81import com.android.server.PackageManagerBackupAgent.Metadata;
82
Christopher Tate2efd2db2011-07-19 16:32:49 -070083import java.io.BufferedInputStream;
84import java.io.BufferedOutputStream;
85import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070086import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070087import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070088import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070089import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070090import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080092import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070093import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070094import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070095import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070096import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070097import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070098import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070099import java.security.InvalidAlgorithmParameterException;
100import java.security.InvalidKeyException;
101import java.security.Key;
102import java.security.NoSuchAlgorithmException;
103import java.security.SecureRandom;
104import java.security.spec.InvalidKeySpecException;
105import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700106import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400107import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700108import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700109import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400110import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700111import java.util.HashSet;
112import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700113import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700114import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800115import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700116import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700117import java.util.zip.Deflater;
118import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700119import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700120
Christopher Tate2efd2db2011-07-19 16:32:49 -0700121import javax.crypto.BadPaddingException;
122import javax.crypto.Cipher;
123import javax.crypto.CipherInputStream;
124import javax.crypto.CipherOutputStream;
125import javax.crypto.IllegalBlockSizeException;
126import javax.crypto.NoSuchPaddingException;
127import javax.crypto.SecretKey;
128import javax.crypto.SecretKeyFactory;
129import javax.crypto.spec.IvParameterSpec;
130import javax.crypto.spec.PBEKeySpec;
131import javax.crypto.spec.SecretKeySpec;
132
Christopher Tate487529a2009-04-29 14:03:25 -0700133class BackupManagerService extends IBackupManager.Stub {
134 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700135 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700136 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700137
138 // Name and current contents version of the full-backup manifest file
139 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
140 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700141 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
142 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700143 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700144
Christopher Tate73d73692012-01-20 17:11:31 -0800145 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
146
Christopher Tate49401dd2009-07-01 12:34:29 -0700147 // How often we perform a backup pass. Privileged external callers can
148 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700149 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700150
Dan Egnorc1c49c02009-10-30 17:35:39 -0700151 // Random variation in backup scheduling time to avoid server load spikes
152 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
153
Christopher Tate8031a3d2009-07-06 16:36:05 -0700154 // The amount of time between the initial provisioning of the device and
155 // the first backup pass.
156 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
157
Christopher Tate45281862010-03-05 15:46:30 -0800158 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
159 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
160 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700161 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700162 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700163 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700164 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700165 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700166 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
167 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800168 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700169 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
170 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700171
Christopher Tate8e294d42011-08-31 20:37:12 -0700172 // backup task state machine tick
173 static final int MSG_BACKUP_RESTORE_STEP = 20;
174 static final int MSG_OP_COMPLETE = 21;
175
Christopher Tatec7b31e32009-06-10 15:49:30 -0700176 // Timeout interval for deciding that a bind or clear-data has taken too long
177 static final long TIMEOUT_INTERVAL = 10 * 1000;
178
Christopher Tate44a27902010-01-27 17:15:49 -0800179 // Timeout intervals for agent backup & restore operations
180 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700181 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700182 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800183 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
184
Christopher Tate2efd2db2011-07-19 16:32:49 -0700185 // User confirmation timeout for a full backup/restore operation. It's this long in
186 // order to give them time to enter the backup password.
187 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700188
Christopher Tate487529a2009-04-29 14:03:25 -0700189 private Context mContext;
190 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800191 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700192 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700193 private PowerManager mPowerManager;
194 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700195 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800196 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700197
Christopher Tate73e02522009-07-15 14:18:26 -0700198 boolean mEnabled; // access to this is synchronized on 'this'
199 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800200 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700201 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800202 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800203 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700204 PendingIntent mRunBackupIntent, mRunInitIntent;
205 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700206 // map UIDs to the set of participating packages under that UID
207 final SparseArray<HashSet<String>> mBackupParticipants
208 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700209 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700210 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700211 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700212
Christopher Tatecc55f812011-08-16 16:06:53 -0700213 BackupRequest(String pkgName) {
214 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700215 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700216
217 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700218 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700219 }
Christopher Tate46758122009-05-06 11:22:00 -0700220 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800221 // Backups that we haven't started yet. Keys are package names.
222 HashMap<String,BackupRequest> mPendingBackups
223 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700224
225 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700226 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700227
228 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700229 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700230
Christopher Tate043dadc2009-06-02 16:11:00 -0700231 // The thread performing the sequence of queued backups binds to each app's agent
232 // in succession. Bind notifications are asynchronously delivered through the
233 // Activity Manager; use this lock object to signal when a requested binding has
234 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700235 final Object mAgentConnectLock = new Object();
236 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700237 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700238 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700239 volatile long mLastBackupPass;
240 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700241
Christopher Tate6de74ff2012-01-17 15:20:32 -0800242 // For debugging, we maintain a progress trace of operations during backup
243 static final boolean DEBUG_BACKUP_TRACE = true;
244 final List<String> mBackupTrace = new ArrayList<String>();
245
Christopher Tate55f931a2009-09-29 17:17:34 -0700246 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700247 final Object mClearDataLock = new Object();
248 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700249
Christopher Tate91717492009-06-26 21:07:13 -0700250 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700251 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700252 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700253 String mCurrentTransport;
254 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800255 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700256
Christopher Tate97ea1222012-05-17 14:59:41 -0700257 // Watch the device provisioning operation during setup
258 ContentObserver mProvisionedObserver;
259
260 class ProvisionedObserver extends ContentObserver {
261 public ProvisionedObserver(Handler handler) {
262 super(handler);
263 }
264
265 public void onChange(boolean selfChange) {
266 final boolean wasProvisioned = mProvisioned;
267 final boolean isProvisioned = deviceIsProvisioned();
268 // latch: never unprovision
269 mProvisioned = wasProvisioned || isProvisioned;
270 if (MORE_DEBUG) {
271 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
272 + " is=" + isProvisioned + " now=" + mProvisioned);
273 }
274
275 synchronized (mQueueLock) {
276 if (mProvisioned && !wasProvisioned && mEnabled) {
277 // we're now good to go, so start the backup alarms
278 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
279 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
280 }
281 }
282 }
283 }
284
Christopher Tate2d449afe2010-03-29 19:14:24 -0700285 class RestoreGetSetsParams {
286 public IBackupTransport transport;
287 public ActiveRestoreSession session;
288 public IRestoreObserver observer;
289
290 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
291 IRestoreObserver _observer) {
292 transport = _transport;
293 session = _session;
294 observer = _observer;
295 }
296 }
297
Christopher Tate73e02522009-07-15 14:18:26 -0700298 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700299 public IBackupTransport transport;
300 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700301 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800302 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800303 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700304 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700305 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800306
307 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700308 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800309 transport = _transport;
310 observer = _obs;
311 token = _token;
312 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800313 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700314 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700315 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800316 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700317
Chris Tate249345b2010-10-29 12:57:04 -0700318 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
319 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700320 transport = _transport;
321 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700322 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800323 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800324 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700325 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700326 filterSet = null;
327 }
328
329 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
330 String[] _filterSet, boolean _needFullBackup) {
331 transport = _transport;
332 observer = _obs;
333 token = _token;
334 pkgInfo = null;
335 pmToken = 0;
336 needFullBackup = _needFullBackup;
337 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700338 }
339 }
340
Christopher Tate73e02522009-07-15 14:18:26 -0700341 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700342 public IBackupTransport transport;
343 public PackageInfo packageInfo;
344
345 ClearParams(IBackupTransport _transport, PackageInfo _info) {
346 transport = _transport;
347 packageInfo = _info;
348 }
349 }
350
Christopher Tate4a627c72011-04-01 14:43:32 -0700351 class FullParams {
352 public ParcelFileDescriptor fd;
353 public final AtomicBoolean latch;
354 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700355 public String curPassword; // filled in by the confirmation step
356 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700357
358 FullParams() {
359 latch = new AtomicBoolean(false);
360 }
361 }
362
363 class FullBackupParams extends FullParams {
364 public boolean includeApks;
365 public boolean includeShared;
366 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700367 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700368 public String[] packages;
369
370 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700371 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700372 fd = output;
373 includeApks = saveApks;
374 includeShared = saveShared;
375 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700376 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700377 packages = pkgList;
378 }
379 }
380
381 class FullRestoreParams extends FullParams {
382 FullRestoreParams(ParcelFileDescriptor input) {
383 fd = input;
384 }
385 }
386
Christopher Tate44a27902010-01-27 17:15:49 -0800387 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
388 // token is the index of the entry in the pending-operations list.
389 static final int OP_PENDING = 0;
390 static final int OP_ACKNOWLEDGED = 1;
391 static final int OP_TIMEOUT = -1;
392
Christopher Tate8e294d42011-08-31 20:37:12 -0700393 class Operation {
394 public int state;
395 public BackupRestoreTask callback;
396
397 Operation(int initialState, BackupRestoreTask callbackObj) {
398 state = initialState;
399 callback = callbackObj;
400 }
401 }
402 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800403 final Object mCurrentOpLock = new Object();
404 final Random mTokenGenerator = new Random();
405
Christopher Tate4a627c72011-04-01 14:43:32 -0700406 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
407
Christopher Tate5cb400b2009-06-25 16:03:14 -0700408 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700409 File mBaseStateDir;
410 File mDataDir;
411 File mJournalDir;
412 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700413
Christopher Tate2efd2db2011-07-19 16:32:49 -0700414 // Backup password, if any, and the file where it's saved. What is stored is not the
415 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
416 // persisted) salt. Validation is performed by running the challenge text through the
417 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
418 // the saved hash string, then the challenge text matches the originally supplied
419 // password text.
420 private final SecureRandom mRng = new SecureRandom();
421 private String mPasswordHash;
422 private File mPasswordHashFile;
423 private byte[] mPasswordSalt;
424
425 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
426 static final int PBKDF2_HASH_ROUNDS = 10000;
427 static final int PBKDF2_KEY_SIZE = 256; // bits
428 static final int PBKDF2_SALT_SIZE = 512; // bits
429 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
430
Christopher Tate84725812010-02-04 15:52:40 -0800431 // Keep a log of all the apps we've ever backed up, and what the
432 // dataset tokens are for both the current backup dataset and
433 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700434 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700435 HashSet<String> mEverStoredApps = new HashSet<String>();
436
Christopher Tateb49ceb32010-02-08 16:22:24 -0800437 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800438 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800439 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800440 long mAncestralToken = 0;
441 long mCurrentToken = 0;
442
Christopher Tate4cc86e12009-09-21 19:36:51 -0700443 // Persistently track the need to do a full init
444 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
445 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700446
Christopher Tate4a627c72011-04-01 14:43:32 -0700447 // Utility: build a new random integer token
448 int generateToken() {
449 int token;
450 do {
451 synchronized (mTokenGenerator) {
452 token = mTokenGenerator.nextInt();
453 }
454 } while (token < 0);
455 return token;
456 }
457
Christopher Tate44a27902010-01-27 17:15:49 -0800458 // ----- Asynchronous backup/restore handler thread -----
459
460 private class BackupHandler extends Handler {
461 public BackupHandler(Looper looper) {
462 super(looper);
463 }
464
465 public void handleMessage(Message msg) {
466
467 switch (msg.what) {
468 case MSG_RUN_BACKUP:
469 {
470 mLastBackupPass = System.currentTimeMillis();
471 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
472
473 IBackupTransport transport = getTransport(mCurrentTransport);
474 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800475 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700476 synchronized (mQueueLock) {
477 mBackupRunning = false;
478 }
Christopher Tate44a27902010-01-27 17:15:49 -0800479 mWakelock.release();
480 break;
481 }
482
483 // snapshot the pending-backup set and work on that
484 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800485 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800486 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800487 // Do we have any work to do? Construct the work queue
488 // then release the synchronization lock to actually run
489 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800490 if (mPendingBackups.size() > 0) {
491 for (BackupRequest b: mPendingBackups.values()) {
492 queue.add(b);
493 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800494 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800495 mPendingBackups.clear();
496
497 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800498 mJournal = null;
499
Christopher Tate44a27902010-01-27 17:15:49 -0800500 }
501 }
Christopher Tatec61da312010-02-05 10:41:27 -0800502
Christopher Tate8e294d42011-08-31 20:37:12 -0700503 // At this point, we have started a new journal file, and the old
504 // file identity is being passed to the backup processing task.
505 // When it completes successfully, that old journal file will be
506 // deleted. If we crash prior to that, the old journal is parsed
507 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800508 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700509 // Spin up a backup state sequence and set it running
510 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
511 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
512 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800513 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800514 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700515 synchronized (mQueueLock) {
516 mBackupRunning = false;
517 }
Christopher Tatec61da312010-02-05 10:41:27 -0800518 mWakelock.release();
519 }
Christopher Tate44a27902010-01-27 17:15:49 -0800520 break;
521 }
522
Christopher Tate8e294d42011-08-31 20:37:12 -0700523 case MSG_BACKUP_RESTORE_STEP:
524 {
525 try {
526 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
527 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
528 task.execute();
529 } catch (ClassCastException e) {
530 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
531 }
532 break;
533 }
534
535 case MSG_OP_COMPLETE:
536 {
537 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700538 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
539 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700540 } catch (ClassCastException e) {
541 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
542 }
543 break;
544 }
545
Christopher Tate44a27902010-01-27 17:15:49 -0800546 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700547 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700548 // TODO: refactor full backup to be a looper-based state machine
549 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700550 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700551 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
552 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700553 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700554 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700555 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800556 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700557 }
Christopher Tate44a27902010-01-27 17:15:49 -0800558
559 case MSG_RUN_RESTORE:
560 {
561 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800562 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700563 PerformRestoreTask task = new PerformRestoreTask(
564 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700565 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700566 params.needFullBackup, params.filterSet);
567 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
568 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800569 break;
570 }
571
Christopher Tate75a99702011-05-18 16:28:19 -0700572 case MSG_RUN_FULL_RESTORE:
573 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700574 // TODO: refactor full restore to be a looper-based state machine
575 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700576 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700577 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
578 params.curPassword, params.encryptPassword,
579 params.observer, params.latch);
580 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700581 break;
582 }
583
Christopher Tate44a27902010-01-27 17:15:49 -0800584 case MSG_RUN_CLEAR:
585 {
586 ClearParams params = (ClearParams)msg.obj;
587 (new PerformClearTask(params.transport, params.packageInfo)).run();
588 break;
589 }
590
591 case MSG_RUN_INITIALIZE:
592 {
593 HashSet<String> queue;
594
595 // Snapshot the pending-init queue and work on that
596 synchronized (mQueueLock) {
597 queue = new HashSet<String>(mPendingInits);
598 mPendingInits.clear();
599 }
600
601 (new PerformInitializeTask(queue)).run();
602 break;
603 }
604
Christopher Tate2d449afe2010-03-29 19:14:24 -0700605 case MSG_RUN_GET_RESTORE_SETS:
606 {
607 // Like other async operations, this is entered with the wakelock held
608 RestoreSet[] sets = null;
609 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
610 try {
611 sets = params.transport.getAvailableRestoreSets();
612 // cache the result in the active session
613 synchronized (params.session) {
614 params.session.mRestoreSets = sets;
615 }
616 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
617 } catch (Exception e) {
618 Slog.e(TAG, "Error from transport getting set list");
619 } finally {
620 if (params.observer != null) {
621 try {
622 params.observer.restoreSetsAvailable(sets);
623 } catch (RemoteException re) {
624 Slog.e(TAG, "Unable to report listing to observer");
625 } catch (Exception e) {
626 Slog.e(TAG, "Restore observer threw", e);
627 }
628 }
629
Christopher Tate2a935092011-03-03 17:30:32 -0800630 // Done: reset the session timeout clock
631 removeMessages(MSG_RESTORE_TIMEOUT);
632 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
633
Christopher Tate2d449afe2010-03-29 19:14:24 -0700634 mWakelock.release();
635 }
636 break;
637 }
638
Christopher Tate44a27902010-01-27 17:15:49 -0800639 case MSG_TIMEOUT:
640 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700641 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800642 break;
643 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800644
645 case MSG_RESTORE_TIMEOUT:
646 {
647 synchronized (BackupManagerService.this) {
648 if (mActiveRestoreSession != null) {
649 // Client app left the restore session dangling. We know that it
650 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700651 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800652 // up now.
653 Slog.w(TAG, "Restore session timed out; aborting");
654 post(mActiveRestoreSession.new EndRestoreRunnable(
655 BackupManagerService.this, mActiveRestoreSession));
656 }
657 }
658 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700659
660 case MSG_FULL_CONFIRMATION_TIMEOUT:
661 {
662 synchronized (mFullConfirmations) {
663 FullParams params = mFullConfirmations.get(msg.arg1);
664 if (params != null) {
665 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
666
667 // Release the waiter; timeout == completion
668 signalFullBackupRestoreCompletion(params);
669
670 // Remove the token from the set
671 mFullConfirmations.delete(msg.arg1);
672
673 // Report a timeout to the observer, if any
674 if (params.observer != null) {
675 try {
676 params.observer.onTimeout();
677 } catch (RemoteException e) {
678 /* don't care if the app has gone away */
679 }
680 }
681 } else {
682 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
683 }
684 }
685 break;
686 }
Christopher Tate44a27902010-01-27 17:15:49 -0800687 }
688 }
689 }
690
Christopher Tate6de74ff2012-01-17 15:20:32 -0800691 // ----- Debug-only backup operation trace -----
692 void addBackupTrace(String s) {
693 if (DEBUG_BACKUP_TRACE) {
694 synchronized (mBackupTrace) {
695 mBackupTrace.add(s);
696 }
697 }
698 }
699
700 void clearBackupTrace() {
701 if (DEBUG_BACKUP_TRACE) {
702 synchronized (mBackupTrace) {
703 mBackupTrace.clear();
704 }
705 }
706 }
707
Christopher Tate44a27902010-01-27 17:15:49 -0800708 // ----- Main service implementation -----
709
Christopher Tate487529a2009-04-29 14:03:25 -0700710 public BackupManagerService(Context context) {
711 mContext = context;
712 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700713 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700714 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700715
Christopher Tateb6787f22009-07-02 17:40:45 -0700716 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
717 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700718 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700719
Christopher Tate44a27902010-01-27 17:15:49 -0800720 mBackupManagerBinder = asInterface(asBinder());
721
722 // spin up the backup/restore handler thread
723 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
724 mHandlerThread.start();
725 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
726
Christopher Tate22b87872009-05-04 16:41:53 -0700727 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700728 final ContentResolver resolver = context.getContentResolver();
729 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700730 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700731 mProvisioned = Settings.Secure.getInt(resolver,
732 Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
733 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800734 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700735
736 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
737 resolver.registerContentObserver(
738 Settings.Secure.getUriFor(Settings.Secure.DEVICE_PROVISIONED),
739 false, mProvisionedObserver);
740
Oscar Montemayora8529f62009-11-18 10:14:20 -0800741 // If Encrypted file systems is enabled or disabled, this call will return the
742 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600743 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800744 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700745 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700746
Christopher Tate2efd2db2011-07-19 16:32:49 -0700747 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
748 if (mPasswordHashFile.exists()) {
749 FileInputStream fin = null;
750 DataInputStream in = null;
751 try {
752 fin = new FileInputStream(mPasswordHashFile);
753 in = new DataInputStream(new BufferedInputStream(fin));
754 // integer length of the salt array, followed by the salt,
755 // then the hex pw hash string
756 int saltLen = in.readInt();
757 byte[] salt = new byte[saltLen];
758 in.readFully(salt);
759 mPasswordHash = in.readUTF();
760 mPasswordSalt = salt;
761 } catch (IOException e) {
762 Slog.e(TAG, "Unable to read saved backup pw hash");
763 } finally {
764 try {
765 if (in != null) in.close();
766 if (fin != null) fin.close();
767 } catch (IOException e) {
768 Slog.w(TAG, "Unable to close streams");
769 }
770 }
771 }
772
Christopher Tate4cc86e12009-09-21 19:36:51 -0700773 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700774 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700775 IntentFilter filter = new IntentFilter();
776 filter.addAction(RUN_BACKUP_ACTION);
777 context.registerReceiver(mRunBackupReceiver, filter,
778 android.Manifest.permission.BACKUP, null);
779
780 mRunInitReceiver = new RunInitializeReceiver();
781 filter = new IntentFilter();
782 filter.addAction(RUN_INITIALIZE_ACTION);
783 context.registerReceiver(mRunInitReceiver, filter,
784 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700785
786 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700787 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
788 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
789
Christopher Tate4cc86e12009-09-21 19:36:51 -0700790 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
791 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
792 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
793
Christopher Tatecde87f42009-06-12 12:55:53 -0700794 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700795 mJournalDir = new File(mBaseStateDir, "pending");
796 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700797 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700798
Christopher Tate73e02522009-07-15 14:18:26 -0700799 // Set up the various sorts of package tracking we do
800 initPackageTracking();
801
Christopher Tateabce4e82009-06-18 18:35:32 -0700802 // Build our mapping of uid to backup client services. This implicitly
803 // schedules a backup pass on the Package Manager metadata the first
804 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700805 synchronized (mBackupParticipants) {
806 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700807 }
808
Dan Egnor87a02bc2009-06-17 02:30:10 -0700809 // Set up our transport options and initialize the default transport
810 // TODO: Have transports register themselves somehow?
811 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700812 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700813 ComponentName localName = new ComponentName(context, LocalTransport.class);
814 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700815
Christopher Tate91717492009-06-26 21:07:13 -0700816 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700817 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
818 Settings.Secure.BACKUP_TRANSPORT);
819 if ("".equals(mCurrentTransport)) {
820 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700821 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800822 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700823
824 // Attach to the Google backup transport. When this comes up, it will set
825 // itself as the current transport because we explicitly reset mCurrentTransport
826 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700827 ComponentName transportComponent = new ComponentName("com.google.android.backup",
828 "com.google.android.backup.BackupTransportService");
829 try {
830 // If there's something out there that is supposed to be the Google
831 // backup transport, make sure it's legitimately part of the OS build
832 // and not an app lying about its package name.
833 ApplicationInfo info = mPackageManager.getApplicationInfo(
834 transportComponent.getPackageName(), 0);
835 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
836 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
837 Intent intent = new Intent().setComponent(transportComponent);
838 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
839 } else {
840 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
841 }
842 } catch (PackageManager.NameNotFoundException nnf) {
843 // No such package? No binding.
844 if (DEBUG) Slog.v(TAG, "Google transport not present");
845 }
Christopher Tateaa088442009-06-16 18:25:46 -0700846
Christopher Tatecde87f42009-06-12 12:55:53 -0700847 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700848 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700849 parseLeftoverJournals();
850
Christopher Tateb6787f22009-07-02 17:40:45 -0700851 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700852 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700853
854 // Start the backup passes going
855 setBackupEnabled(areEnabled);
856 }
857
858 private class RunBackupReceiver extends BroadcastReceiver {
859 public void onReceive(Context context, Intent intent) {
860 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700861 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700862 if (mPendingInits.size() > 0) {
863 // If there are pending init operations, we process those
864 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700866 try {
867 mAlarmManager.cancel(mRunInitIntent);
868 mRunInitIntent.send();
869 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800870 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700871 // can't really do more than bail here
872 }
873 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800874 // Don't run backups now if we're disabled or not yet
875 // fully set up.
876 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700877 if (!mBackupRunning) {
878 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700879
Christopher Tate336a6492011-10-05 16:05:43 -0700880 // Acquire the wakelock and pass it to the backup thread. it will
881 // be released once backup concludes.
882 mBackupRunning = true;
883 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700884
Christopher Tate336a6492011-10-05 16:05:43 -0700885 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
886 mBackupHandler.sendMessage(msg);
887 } else {
888 Slog.i(TAG, "Backup time but one already running");
889 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700890 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800891 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700892 }
893 }
894 }
895 }
896 }
897 }
898
899 private class RunInitializeReceiver extends BroadcastReceiver {
900 public void onReceive(Context context, Intent intent) {
901 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
902 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700904
905 // Acquire the wakelock and pass it to the init thread. it will
906 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700907 mWakelock.acquire();
908
Christopher Tate4cc86e12009-09-21 19:36:51 -0700909 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700910 mBackupHandler.sendMessage(msg);
911 }
912 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700913 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700914 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700915
Christopher Tate73e02522009-07-15 14:18:26 -0700916 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800917 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700918
Christopher Tate84725812010-02-04 15:52:40 -0800919 // Remember our ancestral dataset
920 mTokenFile = new File(mBaseStateDir, "ancestral");
921 try {
922 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800923 int version = tf.readInt();
924 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
925 mAncestralToken = tf.readLong();
926 mCurrentToken = tf.readLong();
927
928 int numPackages = tf.readInt();
929 if (numPackages >= 0) {
930 mAncestralPackages = new HashSet<String>();
931 for (int i = 0; i < numPackages; i++) {
932 String pkgName = tf.readUTF();
933 mAncestralPackages.add(pkgName);
934 }
935 }
936 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800937 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800938 } catch (FileNotFoundException fnf) {
939 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800940 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800941 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800942 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800943 }
944
Christopher Tatee97e8072009-07-15 16:45:50 -0700945 // Keep a log of what apps we've ever backed up. Because we might have
946 // rebooted in the middle of an operation that was removing something from
947 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700948 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700949 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700950
Christopher Tatee97e8072009-07-15 16:45:50 -0700951 // If we were in the middle of removing something from the ever-backed-up
952 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700953 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700954 if (tempProcessedFile.exists()) {
955 tempProcessedFile.delete();
956 }
957
Dan Egnor852f8e42009-09-30 11:20:45 -0700958 // If there are previous contents, parse them out then start a new
959 // file to continue the recordkeeping.
960 if (mEverStored.exists()) {
961 RandomAccessFile temp = null;
962 RandomAccessFile in = null;
963
964 try {
965 temp = new RandomAccessFile(tempProcessedFile, "rws");
966 in = new RandomAccessFile(mEverStored, "r");
967
968 while (true) {
969 PackageInfo info;
970 String pkg = in.readUTF();
971 try {
972 info = mPackageManager.getPackageInfo(pkg, 0);
973 mEverStoredApps.add(pkg);
974 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700975 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700976 } catch (NameNotFoundException e) {
977 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700978 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700979 }
980 }
981 } catch (EOFException e) {
982 // Once we've rewritten the backup history log, atomically replace the
983 // old one with the new one then reopen the file for continuing use.
984 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800985 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700986 }
987 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800988 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700989 } finally {
990 try { if (temp != null) temp.close(); } catch (IOException e) {}
991 try { if (in != null) in.close(); } catch (IOException e) {}
992 }
993 }
994
Christopher Tate73e02522009-07-15 14:18:26 -0700995 // Register for broadcasts about package install, etc., so we can
996 // update the provider list.
997 IntentFilter filter = new IntentFilter();
998 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
999 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1000 filter.addDataScheme("package");
1001 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001002 // Register for events related to sdcard installation.
1003 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001004 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1005 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001006 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001007 }
1008
Christopher Tatecde87f42009-06-12 12:55:53 -07001009 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001010 for (File f : mJournalDir.listFiles()) {
1011 if (mJournal == null || f.compareTo(mJournal) != 0) {
1012 // This isn't the current journal, so it must be a leftover. Read
1013 // out the package names mentioned there and schedule them for
1014 // backup.
1015 RandomAccessFile in = null;
1016 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001017 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001018 in = new RandomAccessFile(f, "r");
1019 while (true) {
1020 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001021 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001022 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001023 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001024 } catch (EOFException e) {
1025 // no more data; we're done
1026 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001027 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001028 } finally {
1029 // close/delete the file
1030 try { if (in != null) in.close(); } catch (IOException e) {}
1031 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001032 }
1033 }
1034 }
1035 }
1036
Christopher Tate2efd2db2011-07-19 16:32:49 -07001037 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1038 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1039 }
1040
1041 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1042 try {
1043 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1044 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1045 return keyFactory.generateSecret(ks);
1046 } catch (InvalidKeySpecException e) {
1047 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1048 } catch (NoSuchAlgorithmException e) {
1049 Slog.e(TAG, "PBKDF2 unavailable!");
1050 }
1051 return null;
1052 }
1053
1054 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1055 SecretKey key = buildPasswordKey(pw, salt, rounds);
1056 if (key != null) {
1057 return byteArrayToHex(key.getEncoded());
1058 }
1059 return null;
1060 }
1061
1062 private String byteArrayToHex(byte[] data) {
1063 StringBuilder buf = new StringBuilder(data.length * 2);
1064 for (int i = 0; i < data.length; i++) {
1065 buf.append(Byte.toHexString(data[i], true));
1066 }
1067 return buf.toString();
1068 }
1069
1070 private byte[] hexToByteArray(String digits) {
1071 final int bytes = digits.length() / 2;
1072 if (2*bytes != digits.length()) {
1073 throw new IllegalArgumentException("Hex string must have an even number of digits");
1074 }
1075
1076 byte[] result = new byte[bytes];
1077 for (int i = 0; i < digits.length(); i += 2) {
1078 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1079 }
1080 return result;
1081 }
1082
1083 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1084 char[] mkAsChar = new char[pwBytes.length];
1085 for (int i = 0; i < pwBytes.length; i++) {
1086 mkAsChar[i] = (char) pwBytes[i];
1087 }
1088
1089 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1090 return checksum.getEncoded();
1091 }
1092
1093 // Used for generating random salts or passwords
1094 private byte[] randomBytes(int bits) {
1095 byte[] array = new byte[bits / 8];
1096 mRng.nextBytes(array);
1097 return array;
1098 }
1099
1100 // Backup password management
1101 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001102 // First, on an encrypted device we require matching the device pw
1103 final boolean isEncrypted;
1104 try {
1105 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1106 if (isEncrypted) {
1107 if (DEBUG) {
1108 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1109 }
1110 // 0 means the password validated
1111 // -2 means device not encrypted
1112 // Any other result is either password failure or an error condition,
1113 // so we refuse the match
1114 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1115 if (result == 0) {
1116 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1117 return true;
1118 } else if (result != -2) {
1119 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1120 return false;
1121 } else {
1122 // ...else the device is supposedly not encrypted. HOWEVER, the
1123 // query about the encryption state said that the device *is*
1124 // encrypted, so ... we may have a problem. Log it and refuse
1125 // the backup.
1126 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1127 return false;
1128 }
1129 }
1130 } catch (Exception e) {
1131 // Something went wrong talking to the mount service. This is very bad;
1132 // assume that we fail password validation.
1133 return false;
1134 }
1135
Christopher Tate2efd2db2011-07-19 16:32:49 -07001136 if (mPasswordHash == null) {
1137 // no current password case -- require that 'currentPw' be null or empty
1138 if (candidatePw == null || "".equals(candidatePw)) {
1139 return true;
1140 } // else the non-empty candidate does not match the empty stored pw
1141 } else {
1142 // hash the stated current pw and compare to the stored one
1143 if (candidatePw != null && candidatePw.length() > 0) {
1144 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1145 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1146 // candidate hash matches the stored hash -- the password matches
1147 return true;
1148 }
1149 } // else the stored pw is nonempty but the candidate is empty; no match
1150 }
1151 return false;
1152 }
1153
1154 @Override
1155 public boolean setBackupPassword(String currentPw, String newPw) {
1156 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1157 "setBackupPassword");
1158
1159 // If the supplied pw doesn't hash to the the saved one, fail
1160 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1161 return false;
1162 }
1163
1164 // Clearing the password is okay
1165 if (newPw == null || newPw.isEmpty()) {
1166 if (mPasswordHashFile.exists()) {
1167 if (!mPasswordHashFile.delete()) {
1168 // Unable to delete the old pw file, so fail
1169 Slog.e(TAG, "Unable to clear backup password");
1170 return false;
1171 }
1172 }
1173 mPasswordHash = null;
1174 mPasswordSalt = null;
1175 return true;
1176 }
1177
1178 try {
1179 // Okay, build the hash of the new backup password
1180 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1181 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1182
1183 OutputStream pwf = null, buffer = null;
1184 DataOutputStream out = null;
1185 try {
1186 pwf = new FileOutputStream(mPasswordHashFile);
1187 buffer = new BufferedOutputStream(pwf);
1188 out = new DataOutputStream(buffer);
1189 // integer length of the salt array, followed by the salt,
1190 // then the hex pw hash string
1191 out.writeInt(salt.length);
1192 out.write(salt);
1193 out.writeUTF(newPwHash);
1194 out.flush();
1195 mPasswordHash = newPwHash;
1196 mPasswordSalt = salt;
1197 return true;
1198 } finally {
1199 if (out != null) out.close();
1200 if (buffer != null) buffer.close();
1201 if (pwf != null) pwf.close();
1202 }
1203 } catch (IOException e) {
1204 Slog.e(TAG, "Unable to set backup password");
1205 }
1206 return false;
1207 }
1208
1209 @Override
1210 public boolean hasBackupPassword() {
1211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1212 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001213
1214 try {
1215 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1216 || (mPasswordHash != null && mPasswordHash.length() > 0);
1217 } catch (Exception e) {
1218 // If we can't talk to the mount service we have a serious problem; fail
1219 // "secure" i.e. assuming that we require a password
1220 return true;
1221 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001222 }
1223
Christopher Tate4cc86e12009-09-21 19:36:51 -07001224 // Maintain persistent state around whether need to do an initialize operation.
1225 // Must be called with the queue lock held.
1226 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001227 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001228 + " on transport " + transportName);
1229 try {
1230 IBackupTransport transport = getTransport(transportName);
1231 String transportDirName = transport.transportDirName();
1232 File stateDir = new File(mBaseStateDir, transportDirName);
1233 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1234
1235 if (isPending) {
1236 // We need an init before we can proceed with sending backup data.
1237 // Record that with an entry in our set of pending inits, as well as
1238 // journaling it via creation of a sentinel file.
1239 mPendingInits.add(transportName);
1240 try {
1241 (new FileOutputStream(initPendingFile)).close();
1242 } catch (IOException ioe) {
1243 // Something is badly wrong with our permissions; just try to move on
1244 }
1245 } else {
1246 // No more initialization needed; wipe the journal and reset our state.
1247 initPendingFile.delete();
1248 mPendingInits.remove(transportName);
1249 }
1250 } catch (RemoteException e) {
1251 // can't happen; the transport is local
1252 }
1253 }
1254
Christopher Tated55e18a2009-09-21 10:12:59 -07001255 // Reset all of our bookkeeping, in response to having been told that
1256 // the backend data has been wiped [due to idle expiry, for example],
1257 // so we must re-upload all saved settings.
1258 void resetBackupState(File stateFileDir) {
1259 synchronized (mQueueLock) {
1260 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001261 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001262 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001263
Christopher Tate84725812010-02-04 15:52:40 -08001264 mCurrentToken = 0;
1265 writeRestoreTokens();
1266
Christopher Tated55e18a2009-09-21 10:12:59 -07001267 // Remove all the state files
1268 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001269 // ... but don't touch the needs-init sentinel
1270 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1271 sf.delete();
1272 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001273 }
Christopher Tate45597642011-04-04 16:59:21 -07001274 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001275
Christopher Tate45597642011-04-04 16:59:21 -07001276 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001277 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001278 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001279 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001280 HashSet<String> participants = mBackupParticipants.valueAt(i);
1281 if (participants != null) {
1282 for (String packageName : participants) {
1283 dataChangedImpl(packageName);
1284 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001285 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001286 }
1287 }
1288 }
1289
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001290 // Add a transport to our set of available backends. If 'transport' is null, this
1291 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001292 private void registerTransport(String name, IBackupTransport transport) {
1293 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001294 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001295 if (transport != null) {
1296 mTransports.put(name, transport);
1297 } else {
1298 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001299 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001300 mCurrentTransport = null;
1301 }
1302 // Nothing further to do in the unregistration case
1303 return;
1304 }
Christopher Tate91717492009-06-26 21:07:13 -07001305 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001306
1307 // If the init sentinel file exists, we need to be sure to perform the init
1308 // as soon as practical. We also create the state directory at registration
1309 // time to ensure it's present from the outset.
1310 try {
1311 String transportName = transport.transportDirName();
1312 File stateDir = new File(mBaseStateDir, transportName);
1313 stateDir.mkdirs();
1314
1315 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1316 if (initSentinel.exists()) {
1317 synchronized (mQueueLock) {
1318 mPendingInits.add(transportName);
1319
1320 // TODO: pick a better starting time than now + 1 minute
1321 long delay = 1000 * 60; // one minute, in milliseconds
1322 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1323 System.currentTimeMillis() + delay, mRunInitIntent);
1324 }
1325 }
1326 } catch (RemoteException e) {
1327 // can't happen, the transport is local
1328 }
Christopher Tate91717492009-06-26 21:07:13 -07001329 }
1330
Christopher Tate3799bc22009-05-06 16:13:56 -07001331 // ----- Track installation/removal of packages -----
1332 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1333 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001335
Christopher Tate3799bc22009-05-06 16:13:56 -07001336 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001337 boolean replacing = false;
1338 boolean added = false;
1339 Bundle extras = intent.getExtras();
1340 String pkgList[] = null;
1341 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001342 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001343 Uri uri = intent.getData();
1344 if (uri == null) {
1345 return;
1346 }
1347 String pkgName = uri.getSchemeSpecificPart();
1348 if (pkgName != null) {
1349 pkgList = new String[] { pkgName };
1350 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001351 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1352 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001353 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001354 added = true;
1355 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001356 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001357 added = false;
1358 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1359 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001360
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001361 if (pkgList == null || pkgList.length == 0) {
1362 return;
1363 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001364
1365 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001366 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001367 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001368 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001369 // This is the package-replaced case; we just remove the entry
1370 // under the old uid and fall through to re-add.
1371 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001372 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001373 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001374 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001375 } else {
1376 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001377 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1378 } else {
1379 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001380 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001381 }
1382 }
1383 }
1384 }
1385 };
1386
Dan Egnor87a02bc2009-06-17 02:30:10 -07001387 // ----- Track connection to GoogleBackupTransport service -----
1388 ServiceConnection mGoogleConnection = new ServiceConnection() {
1389 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001390 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001391 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001392 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001393 }
1394
1395 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001397 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001398 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001399 }
1400 };
1401
Christopher Tate0bacfd22012-01-11 14:41:19 -08001402 // Add the backup agents in the given packages to our set of known backup participants.
1403 // If 'packageNames' is null, adds all backup agents in the whole system.
1404 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001405 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001406 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001407 if (packageNames != null) {
1408 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1409 for (String packageName : packageNames) {
1410 addPackageParticipantsLockedInner(packageName, targetApps);
1411 }
1412 } else {
1413 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1414 addPackageParticipantsLockedInner(null, targetApps);
1415 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001416 }
1417
Christopher Tate181fafa2009-05-14 11:12:14 -07001418 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001419 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001420 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001421 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001422 }
1423
Dan Egnorefe52642009-06-24 00:16:33 -07001424 for (PackageInfo pkg : targetPkgs) {
1425 if (packageName == null || pkg.packageName.equals(packageName)) {
1426 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001427 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001428 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001429 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001430 mBackupParticipants.put(uid, set);
1431 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001432 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001433 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001434
1435 // If we've never seen this app before, schedule a backup for it
1436 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001437 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001438 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001439 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001440 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001441 }
Christopher Tate487529a2009-04-29 14:03:25 -07001442 }
1443 }
1444
Christopher Tate0bacfd22012-01-11 14:41:19 -08001445 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001446 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001447 if (packageNames == null) {
1448 Slog.w(TAG, "removePackageParticipants with null list");
1449 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001450 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001451
Christopher Tatea3d55342012-03-27 13:16:18 -07001452 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1453 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001454 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001455 // Known previous UID, so we know which package set to check
1456 HashSet<String> set = mBackupParticipants.get(oldUid);
1457 if (set != null && set.contains(pkg)) {
1458 removePackageFromSetLocked(set, pkg);
1459 if (set.isEmpty()) {
1460 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1461 mBackupParticipants.remove(oldUid);
1462 }
1463 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001464 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001465 }
1466
Christopher Tatea3d55342012-03-27 13:16:18 -07001467 private void removePackageFromSetLocked(final HashSet<String> set,
1468 final String packageName) {
1469 if (set.contains(packageName)) {
1470 // Found it. Remove this one package from the bookkeeping, and
1471 // if it's the last participating app under this uid we drop the
1472 // (now-empty) set as well.
1473 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
1474 removeEverBackedUp(packageName);
1475 set.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001476 }
1477 }
1478
Christopher Tate181fafa2009-05-14 11:12:14 -07001479 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001480 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001481 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001482 int flags = PackageManager.GET_SIGNATURES;
1483 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1484 int N = packages.size();
1485 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001486 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001487 try {
1488 ApplicationInfo app = pkg.applicationInfo;
1489 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001490 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001491 packages.remove(a);
1492 }
1493 else {
1494 // we will need the shared library path, so look that up and store it here
1495 app = mPackageManager.getApplicationInfo(pkg.packageName,
1496 PackageManager.GET_SHARED_LIBRARY_FILES);
1497 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1498 }
1499 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001500 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001501 }
1502 }
Dan Egnorefe52642009-06-24 00:16:33 -07001503 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001504 }
Christopher Tateaa088442009-06-16 18:25:46 -07001505
Christopher Tate84725812010-02-04 15:52:40 -08001506 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001507 // backed up at least once
1508 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001509 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1510
1511 synchronized (mEverStoredApps) {
1512 if (!mEverStoredApps.add(packageName)) return;
1513
1514 RandomAccessFile out = null;
1515 try {
1516 out = new RandomAccessFile(mEverStored, "rws");
1517 out.seek(out.length());
1518 out.writeUTF(packageName);
1519 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001520 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001521 } finally {
1522 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001523 }
1524 }
1525 }
1526
Christopher Tatee97e8072009-07-15 16:45:50 -07001527 // Remove our awareness of having ever backed up the given package
1528 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001529 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1530 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001531
Dan Egnor852f8e42009-09-30 11:20:45 -07001532 synchronized (mEverStoredApps) {
1533 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1534 // we'll recognize on initialization time that the package no longer
1535 // exists and fix it up then.
1536 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1537 RandomAccessFile known = null;
1538 try {
1539 known = new RandomAccessFile(tempKnownFile, "rws");
1540 mEverStoredApps.remove(packageName);
1541 for (String s : mEverStoredApps) {
1542 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001543 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001544 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001545 known.close();
1546 known = null;
1547 if (!tempKnownFile.renameTo(mEverStored)) {
1548 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1549 }
1550 } catch (IOException e) {
1551 // Bad: we couldn't create the new copy. For safety's sake we
1552 // abandon the whole process and remove all what's-backed-up
1553 // state entirely, meaning we'll force a backup pass for every
1554 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001556 mEverStoredApps.clear();
1557 tempKnownFile.delete();
1558 mEverStored.delete();
1559 } finally {
1560 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001561 }
1562 }
1563 }
1564
Christopher Tateb49ceb32010-02-08 16:22:24 -08001565 // Persistently record the current and ancestral backup tokens as well
1566 // as the set of packages with data [supposedly] available in the
1567 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001568 void writeRestoreTokens() {
1569 try {
1570 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001571
1572 // First, the version number of this record, for futureproofing
1573 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1574
1575 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001576 af.writeLong(mAncestralToken);
1577 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001578
1579 // Now write the set of ancestral packages
1580 if (mAncestralPackages == null) {
1581 af.writeInt(-1);
1582 } else {
1583 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001584 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001585 for (String pkgName : mAncestralPackages) {
1586 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001587 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001588 }
1589 }
Christopher Tate84725812010-02-04 15:52:40 -08001590 af.close();
1591 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001592 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001593 }
1594 }
1595
Dan Egnor87a02bc2009-06-17 02:30:10 -07001596 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001597 private IBackupTransport getTransport(String transportName) {
1598 synchronized (mTransports) {
1599 IBackupTransport transport = mTransports.get(transportName);
1600 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001602 }
1603 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001604 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001605 }
1606
Christopher Tatedf01dea2009-06-09 20:45:02 -07001607 // fire off a backup agent, blocking until it attaches or times out
1608 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1609 IBackupAgent agent = null;
1610 synchronized(mAgentConnectLock) {
1611 mConnecting = true;
1612 mConnectedAgent = null;
1613 try {
1614 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001615 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001616
1617 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001618 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001619 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1620 while (mConnecting && mConnectedAgent == null
1621 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001622 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001623 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001624 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001626 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001627 return null;
1628 }
1629 }
1630
1631 // if we timed out with no connect, abort and move on
1632 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001633 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 return null;
1635 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001636 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001637 agent = mConnectedAgent;
1638 }
1639 } catch (RemoteException e) {
1640 // can't happen
1641 }
1642 }
1643 return agent;
1644 }
1645
Christopher Tatec7b31e32009-06-10 15:49:30 -07001646 // clear an application's data, blocking until the operation completes or times out
1647 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001648 // Don't wipe packages marked allowClearUserData=false
1649 try {
1650 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1651 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001652 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001653 + packageName);
1654 return;
1655 }
1656 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001657 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001658 return;
1659 }
1660
Christopher Tatec7b31e32009-06-10 15:49:30 -07001661 ClearDataObserver observer = new ClearDataObserver();
1662
1663 synchronized(mClearDataLock) {
1664 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001665 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001666 mActivityManager.clearApplicationUserData(packageName, observer,
1667 Binder.getOrigCallingUser());
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
2724 // Save associated .obb content if it exists and we did save the apk
2725 // check for .obb and save those too
2726 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2727 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002728 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002729 File[] obbFiles = obbDir.listFiles();
2730 if (obbFiles != null) {
2731 final String obbDirName = obbDir.getAbsolutePath();
2732 for (File obb : obbFiles) {
2733 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2734 obbDirName, obb.getAbsolutePath(), output);
2735 }
2736 }
2737 }
2738 }
2739
Christopher Tate6853fcf2011-08-10 17:52:21 -07002740 private void finalizeBackup(OutputStream out) {
2741 try {
2742 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2743 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2744 out.write(eof);
2745 } catch (IOException e) {
2746 Slog.w(TAG, "Error attempting to finalize backup stream");
2747 }
2748 }
2749
Christopher Tate4a627c72011-04-01 14:43:32 -07002750 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2751 throws IOException {
2752 // Manifest format. All data are strings ending in LF:
2753 // BACKUP_MANIFEST_VERSION, currently 1
2754 //
2755 // Version 1:
2756 // package name
2757 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002758 // platform versionCode
2759 // getInstallerPackageName() for this package (maybe empty)
2760 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002761 // number of signatures == N
2762 // N*: signature byte array in ascii format per Signature.toCharsString()
2763 StringBuilder builder = new StringBuilder(4096);
2764 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2765
2766 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2767 printer.println(pkg.packageName);
2768 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002769 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2770
2771 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2772 printer.println((installerName != null) ? installerName : "");
2773
Christopher Tate4a627c72011-04-01 14:43:32 -07002774 printer.println(withApk ? "1" : "0");
2775 if (pkg.signatures == null) {
2776 printer.println("0");
2777 } else {
2778 printer.println(Integer.toString(pkg.signatures.length));
2779 for (Signature sig : pkg.signatures) {
2780 printer.println(sig.toCharsString());
2781 }
2782 }
2783
2784 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002785 outstream.write(builder.toString().getBytes());
2786 outstream.close();
2787 }
2788
2789 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002790 if (pkg != null) {
2791 final ApplicationInfo app = pkg.applicationInfo;
2792 if (app != null) {
2793 try {
2794 // unbind and tidy up even on timeout or failure, just in case
2795 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002796
Christopher Tateb0628bf2011-06-02 15:08:13 -07002797 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002798 if (app.uid != Process.SYSTEM_UID
2799 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002800 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002801 mActivityManager.killApplicationProcess(app.processName, app.uid);
2802 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002803 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002804 }
2805 } catch (RemoteException e) {
2806 Slog.d(TAG, "Lost app trying to shut down");
2807 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002808 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002809 }
2810 }
2811
2812 // wrappers for observer use
2813 void sendStartBackup() {
2814 if (mObserver != null) {
2815 try {
2816 mObserver.onStartBackup();
2817 } catch (RemoteException e) {
2818 Slog.w(TAG, "full backup observer went away: startBackup");
2819 mObserver = null;
2820 }
2821 }
2822 }
2823
2824 void sendOnBackupPackage(String name) {
2825 if (mObserver != null) {
2826 try {
2827 // TODO: use a more user-friendly name string
2828 mObserver.onBackupPackage(name);
2829 } catch (RemoteException e) {
2830 Slog.w(TAG, "full backup observer went away: backupPackage");
2831 mObserver = null;
2832 }
2833 }
2834 }
2835
2836 void sendEndBackup() {
2837 if (mObserver != null) {
2838 try {
2839 mObserver.onEndBackup();
2840 } catch (RemoteException e) {
2841 Slog.w(TAG, "full backup observer went away: endBackup");
2842 mObserver = null;
2843 }
2844 }
2845 }
2846 }
2847
2848
Christopher Tate75a99702011-05-18 16:28:19 -07002849 // ----- Full restore from a file/socket -----
2850
2851 // Description of a file in the restore datastream
2852 static class FileMetadata {
2853 String packageName; // name of the owning app
2854 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002855 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002856 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2857 String path; // subpath within the semantic domain
2858 long mode; // e.g. 0666 (actually int)
2859 long mtime; // last mod time, UTC time_t (actually int)
2860 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002861
2862 @Override
2863 public String toString() {
2864 StringBuilder sb = new StringBuilder(128);
2865 sb.append("FileMetadata{");
2866 sb.append(packageName); sb.append(',');
2867 sb.append(type); sb.append(',');
2868 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2869 sb.append(size);
2870 sb.append('}');
2871 return sb.toString();
2872 }
Christopher Tate75a99702011-05-18 16:28:19 -07002873 }
2874
2875 enum RestorePolicy {
2876 IGNORE,
2877 ACCEPT,
2878 ACCEPT_IF_APK
2879 }
2880
2881 class PerformFullRestoreTask implements Runnable {
2882 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002883 String mCurrentPassword;
2884 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002885 IFullBackupRestoreObserver mObserver;
2886 AtomicBoolean mLatchObject;
2887 IBackupAgent mAgent;
2888 String mAgentPackage;
2889 ApplicationInfo mTargetApp;
2890 ParcelFileDescriptor[] mPipes = null;
2891
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002892 long mBytes;
2893
Christopher Tate75a99702011-05-18 16:28:19 -07002894 // possible handling states for a given package in the restore dataset
2895 final HashMap<String, RestorePolicy> mPackagePolicies
2896 = new HashMap<String, RestorePolicy>();
2897
2898 // installer package names for each encountered app, derived from the manifests
2899 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2900
2901 // Signatures for a given package found in its manifest file
2902 final HashMap<String, Signature[]> mManifestSignatures
2903 = new HashMap<String, Signature[]>();
2904
2905 // Packages we've already wiped data on when restoring their first file
2906 final HashSet<String> mClearedPackages = new HashSet<String>();
2907
Christopher Tate728a1c42011-07-28 18:03:03 -07002908 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002909 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002910 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002911 mCurrentPassword = curPassword;
2912 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002913 mObserver = observer;
2914 mLatchObject = latch;
2915 mAgent = null;
2916 mAgentPackage = null;
2917 mTargetApp = null;
2918
2919 // Which packages we've already wiped data on. We prepopulate this
2920 // with a whitelist of packages known to be unclearable.
2921 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002922 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002923
Christopher Tate75a99702011-05-18 16:28:19 -07002924 }
2925
2926 class RestoreFileRunnable implements Runnable {
2927 IBackupAgent mAgent;
2928 FileMetadata mInfo;
2929 ParcelFileDescriptor mSocket;
2930 int mToken;
2931
2932 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2933 ParcelFileDescriptor socket, int token) throws IOException {
2934 mAgent = agent;
2935 mInfo = info;
2936 mToken = token;
2937
2938 // This class is used strictly for process-local binder invocations. The
2939 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2940 // do not automatically get a 'dup'ed descriptor that we can can continue
2941 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2942 // before proceeding to do the restore.
2943 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2944 }
2945
2946 @Override
2947 public void run() {
2948 try {
2949 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2950 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2951 mToken, mBackupManagerBinder);
2952 } catch (RemoteException e) {
2953 // never happens; this is used strictly for local binder calls
2954 }
2955 }
2956 }
2957
2958 @Override
2959 public void run() {
2960 Slog.i(TAG, "--- Performing full-dataset restore ---");
2961 sendStartRestore();
2962
Christopher Tateb0628bf2011-06-02 15:08:13 -07002963 // Are we able to restore shared-storage data?
2964 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002965 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002966 }
2967
Christopher Tate2efd2db2011-07-19 16:32:49 -07002968 FileInputStream rawInStream = null;
2969 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002970 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002971 if (hasBackupPassword()) {
2972 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2973 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2974 return;
2975 }
2976 }
2977
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002978 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002979 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002980 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2981 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002982
2983 // First, parse out the unencrypted/uncompressed header
2984 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002985 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002986 final InputStream in;
2987
2988 boolean okay = false;
2989 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2990 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002991 rawDataIn.readFully(streamHeader);
2992 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2993 if (Arrays.equals(magicBytes, streamHeader)) {
2994 // okay, header looks good. now parse out the rest of the fields.
2995 String s = readHeaderLine(rawInStream);
2996 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2997 // okay, it's a version we recognize
2998 s = readHeaderLine(rawInStream);
2999 compressed = (Integer.parseInt(s) != 0);
3000 s = readHeaderLine(rawInStream);
3001 if (s.equals("none")) {
3002 // no more header to parse; we're good to go
3003 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003004 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003005 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3006 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003007 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003008 }
3009 } else Slog.w(TAG, "Archive is encrypted but no password given");
3010 } else Slog.w(TAG, "Wrong header version: " + s);
3011 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003012
3013 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003014 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003015 return;
3016 }
3017
3018 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003019 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003020
3021 boolean didRestore;
3022 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003023 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003024 } while (didRestore);
3025
Christopher Tatec58efa62011-08-01 19:20:14 -07003026 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003027 } catch (IOException e) {
3028 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003029 } finally {
3030 tearDownPipes();
3031 tearDownAgent(mTargetApp);
3032
3033 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003034 if (rawDataIn != null) rawDataIn.close();
3035 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003036 mInputFile.close();
3037 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003038 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003039 /* nothing we can do about this */
3040 }
3041 synchronized (mCurrentOpLock) {
3042 mCurrentOperations.clear();
3043 }
3044 synchronized (mLatchObject) {
3045 mLatchObject.set(true);
3046 mLatchObject.notifyAll();
3047 }
3048 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003049 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003050 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003051 }
3052 }
3053
Christopher Tate7bdb0962011-07-13 19:30:21 -07003054 String readHeaderLine(InputStream in) throws IOException {
3055 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003056 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003057 while ((c = in.read()) >= 0) {
3058 if (c == '\n') break; // consume and discard the newlines
3059 buffer.append((char)c);
3060 }
3061 return buffer.toString();
3062 }
3063
Christopher Tate2efd2db2011-07-19 16:32:49 -07003064 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3065 InputStream result = null;
3066 try {
3067 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3068
3069 String userSaltHex = readHeaderLine(rawInStream); // 5
3070 byte[] userSalt = hexToByteArray(userSaltHex);
3071
3072 String ckSaltHex = readHeaderLine(rawInStream); // 6
3073 byte[] ckSalt = hexToByteArray(ckSaltHex);
3074
3075 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3076 String userIvHex = readHeaderLine(rawInStream); // 8
3077
3078 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3079
3080 // decrypt the master key blob
3081 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003082 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003083 rounds);
3084 byte[] IV = hexToByteArray(userIvHex);
3085 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3086 c.init(Cipher.DECRYPT_MODE,
3087 new SecretKeySpec(userKey.getEncoded(), "AES"),
3088 ivSpec);
3089 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3090 byte[] mkBlob = c.doFinal(mkCipher);
3091
3092 // first, the master key IV
3093 int offset = 0;
3094 int len = mkBlob[offset++];
3095 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3096 offset += len;
3097 // then the master key itself
3098 len = mkBlob[offset++];
3099 byte[] mk = Arrays.copyOfRange(mkBlob,
3100 offset, offset + len);
3101 offset += len;
3102 // and finally the master key checksum hash
3103 len = mkBlob[offset++];
3104 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3105 offset, offset + len);
3106
3107 // now validate the decrypted master key against the checksum
3108 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3109 if (Arrays.equals(calculatedCk, mkChecksum)) {
3110 ivSpec = new IvParameterSpec(IV);
3111 c.init(Cipher.DECRYPT_MODE,
3112 new SecretKeySpec(mk, "AES"),
3113 ivSpec);
3114 // Only if all of the above worked properly will 'result' be assigned
3115 result = new CipherInputStream(rawInStream, c);
3116 } else Slog.w(TAG, "Incorrect password");
3117 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3118 } catch (InvalidAlgorithmParameterException e) {
3119 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3120 } catch (BadPaddingException e) {
3121 // This case frequently occurs when the wrong password is used to decrypt
3122 // the master key. Use the identical "incorrect password" log text as is
3123 // used in the checksum failure log in order to avoid providing additional
3124 // information to an attacker.
3125 Slog.w(TAG, "Incorrect password");
3126 } catch (IllegalBlockSizeException e) {
3127 Slog.w(TAG, "Invalid block size in master key");
3128 } catch (NoSuchAlgorithmException e) {
3129 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3130 } catch (NoSuchPaddingException e) {
3131 Slog.e(TAG, "Needed padding mechanism unavailable!");
3132 } catch (InvalidKeyException e) {
3133 Slog.w(TAG, "Illegal password; aborting");
3134 } catch (NumberFormatException e) {
3135 Slog.w(TAG, "Can't parse restore data header");
3136 } catch (IOException e) {
3137 Slog.w(TAG, "Can't read input header");
3138 }
3139
3140 return result;
3141 }
3142
Christopher Tate75a99702011-05-18 16:28:19 -07003143 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3144 FileMetadata info;
3145 try {
3146 info = readTarHeaders(instream);
3147 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003148 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003149 dumpFileMetadata(info);
3150 }
3151
3152 final String pkg = info.packageName;
3153 if (!pkg.equals(mAgentPackage)) {
3154 // okay, change in package; set up our various
3155 // bookkeeping if we haven't seen it yet
3156 if (!mPackagePolicies.containsKey(pkg)) {
3157 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3158 }
3159
3160 // Clean up the previous agent relationship if necessary,
3161 // and let the observer know we're considering a new app.
3162 if (mAgent != null) {
3163 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3164 tearDownPipes();
3165 tearDownAgent(mTargetApp);
3166 mTargetApp = null;
3167 mAgentPackage = null;
3168 }
3169 }
3170
3171 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3172 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3173 mPackageInstallers.put(pkg, info.installerPackageName);
3174 // We've read only the manifest content itself at this point,
3175 // so consume the footer before looping around to the next
3176 // input file
3177 skipTarPadding(info.size, instream);
3178 sendOnRestorePackage(pkg);
3179 } else {
3180 // Non-manifest, so it's actual file data. Is this a package
3181 // we're ignoring?
3182 boolean okay = true;
3183 RestorePolicy policy = mPackagePolicies.get(pkg);
3184 switch (policy) {
3185 case IGNORE:
3186 okay = false;
3187 break;
3188
3189 case ACCEPT_IF_APK:
3190 // If we're in accept-if-apk state, then the first file we
3191 // see MUST be the apk.
3192 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3193 if (DEBUG) Slog.d(TAG, "APK file; installing");
3194 // Try to install the app.
3195 String installerName = mPackageInstallers.get(pkg);
3196 okay = installApk(info, installerName, instream);
3197 // good to go; promote to ACCEPT
3198 mPackagePolicies.put(pkg, (okay)
3199 ? RestorePolicy.ACCEPT
3200 : RestorePolicy.IGNORE);
3201 // At this point we've consumed this file entry
3202 // ourselves, so just strip the tar footer and
3203 // go on to the next file in the input stream
3204 skipTarPadding(info.size, instream);
3205 return true;
3206 } else {
3207 // File data before (or without) the apk. We can't
3208 // handle it coherently in this case so ignore it.
3209 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3210 okay = false;
3211 }
3212 break;
3213
3214 case ACCEPT:
3215 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3216 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3217 // we can take the data without the apk, so we
3218 // *want* to do so. skip the apk by declaring this
3219 // one file not-okay without changing the restore
3220 // policy for the package.
3221 okay = false;
3222 }
3223 break;
3224
3225 default:
3226 // Something has gone dreadfully wrong when determining
3227 // the restore policy from the manifest. Ignore the
3228 // rest of this package's data.
3229 Slog.e(TAG, "Invalid policy from manifest");
3230 okay = false;
3231 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3232 break;
3233 }
3234
3235 // If the policy is satisfied, go ahead and set up to pipe the
3236 // data to the agent.
3237 if (DEBUG && okay && mAgent != null) {
3238 Slog.i(TAG, "Reusing existing agent instance");
3239 }
3240 if (okay && mAgent == null) {
3241 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3242
3243 try {
3244 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3245
3246 // If we haven't sent any data to this app yet, we probably
3247 // need to clear it first. Check that.
3248 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003249 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003250 // responsible for coherently managing a full
3251 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003252 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003253 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3254 clearApplicationDataSynchronous(pkg);
3255 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003256 if (DEBUG) Slog.d(TAG, "backup agent ("
3257 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003258 }
3259 mClearedPackages.add(pkg);
3260 } else {
3261 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3262 }
3263
3264 // All set; now set up the IPC and launch the agent
3265 setUpPipes();
3266 mAgent = bindToAgentSynchronous(mTargetApp,
3267 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3268 mAgentPackage = pkg;
3269 } catch (IOException e) {
3270 // fall through to error handling
3271 } catch (NameNotFoundException e) {
3272 // fall through to error handling
3273 }
3274
3275 if (mAgent == null) {
3276 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3277 okay = false;
3278 tearDownPipes();
3279 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3280 }
3281 }
3282
3283 // Sanity check: make sure we never give data to the wrong app. This
3284 // should never happen but a little paranoia here won't go amiss.
3285 if (okay && !pkg.equals(mAgentPackage)) {
3286 Slog.e(TAG, "Restoring data for " + pkg
3287 + " but agent is for " + mAgentPackage);
3288 okay = false;
3289 }
3290
3291 // At this point we have an agent ready to handle the full
3292 // restore data as well as a pipe for sending data to
3293 // that agent. Tell the agent to start reading from the
3294 // pipe.
3295 if (okay) {
3296 boolean agentSuccess = true;
3297 long toCopy = info.size;
3298 final int token = generateToken();
3299 try {
3300 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3301 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003302 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003303 // fire up the app's agent listening on the socket. If
3304 // the agent is running in the system process we can't
3305 // just invoke it asynchronously, so we provide a thread
3306 // for it here.
3307 if (mTargetApp.processName.equals("system")) {
3308 Slog.d(TAG, "system process agent - spinning a thread");
3309 RestoreFileRunnable runner = new RestoreFileRunnable(
3310 mAgent, info, mPipes[0], token);
3311 new Thread(runner).start();
3312 } else {
3313 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3314 info.domain, info.path, info.mode, info.mtime,
3315 token, mBackupManagerBinder);
3316 }
3317 } catch (IOException e) {
3318 // couldn't dup the socket for a process-local restore
3319 Slog.d(TAG, "Couldn't establish restore");
3320 agentSuccess = false;
3321 okay = false;
3322 } catch (RemoteException e) {
3323 // whoops, remote agent went away. We'll eat the content
3324 // ourselves, then, and not copy it over.
3325 Slog.e(TAG, "Agent crashed during full restore");
3326 agentSuccess = false;
3327 okay = false;
3328 }
3329
3330 // Copy over the data if the agent is still good
3331 if (okay) {
3332 boolean pipeOkay = true;
3333 FileOutputStream pipe = new FileOutputStream(
3334 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003335 while (toCopy > 0) {
3336 int toRead = (toCopy > buffer.length)
3337 ? buffer.length : (int)toCopy;
3338 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003339 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003340 if (nRead <= 0) break;
3341 toCopy -= nRead;
3342
3343 // send it to the output pipe as long as things
3344 // are still good
3345 if (pipeOkay) {
3346 try {
3347 pipe.write(buffer, 0, nRead);
3348 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003349 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003350 pipeOkay = false;
3351 }
3352 }
3353 }
3354
3355 // done sending that file! Now we just need to consume
3356 // the delta from info.size to the end of block.
3357 skipTarPadding(info.size, instream);
3358
3359 // and now that we've sent it all, wait for the remote
3360 // side to acknowledge receipt
3361 agentSuccess = waitUntilOperationComplete(token);
3362 }
3363
3364 // okay, if the remote end failed at any point, deal with
3365 // it by ignoring the rest of the restore on it
3366 if (!agentSuccess) {
3367 mBackupHandler.removeMessages(MSG_TIMEOUT);
3368 tearDownPipes();
3369 tearDownAgent(mTargetApp);
3370 mAgent = null;
3371 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3372 }
3373 }
3374
3375 // Problems setting up the agent communication, or an already-
3376 // ignored package: skip to the next tar stream entry by
3377 // reading and discarding this file.
3378 if (!okay) {
3379 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3380 long bytesToConsume = (info.size + 511) & ~511;
3381 while (bytesToConsume > 0) {
3382 int toRead = (bytesToConsume > buffer.length)
3383 ? buffer.length : (int)bytesToConsume;
3384 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003385 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003386 if (nRead <= 0) break;
3387 bytesToConsume -= nRead;
3388 }
3389 }
3390 }
3391 }
3392 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003393 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003394 // treat as EOF
3395 info = null;
3396 }
3397
3398 return (info != null);
3399 }
3400
3401 void setUpPipes() throws IOException {
3402 mPipes = ParcelFileDescriptor.createPipe();
3403 }
3404
3405 void tearDownPipes() {
3406 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003407 try {
3408 mPipes[0].close();
3409 mPipes[0] = null;
3410 mPipes[1].close();
3411 mPipes[1] = null;
3412 } catch (IOException e) {
3413 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003414 }
3415 mPipes = null;
3416 }
3417 }
3418
3419 void tearDownAgent(ApplicationInfo app) {
3420 if (mAgent != null) {
3421 try {
3422 // unbind and tidy up even on timeout or failure, just in case
3423 mActivityManager.unbindBackupAgent(app);
3424
3425 // The agent was running with a stub Application object, so shut it down.
3426 // !!! We hardcode the confirmation UI's package name here rather than use a
3427 // manifest flag! TODO something less direct.
3428 if (app.uid != Process.SYSTEM_UID
3429 && !app.packageName.equals("com.android.backupconfirm")) {
3430 if (DEBUG) Slog.d(TAG, "Killing host process");
3431 mActivityManager.killApplicationProcess(app.processName, app.uid);
3432 } else {
3433 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3434 }
3435 } catch (RemoteException e) {
3436 Slog.d(TAG, "Lost app trying to shut down");
3437 }
3438 mAgent = null;
3439 }
3440 }
3441
3442 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3443 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003444 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003445 int mResult;
3446
3447 public void reset() {
3448 synchronized (mDone) {
3449 mDone.set(false);
3450 }
3451 }
3452
3453 public void waitForCompletion() {
3454 synchronized (mDone) {
3455 while (mDone.get() == false) {
3456 try {
3457 mDone.wait();
3458 } catch (InterruptedException e) { }
3459 }
3460 }
3461 }
3462
3463 int getResult() {
3464 return mResult;
3465 }
3466
3467 @Override
3468 public void packageInstalled(String packageName, int returnCode)
3469 throws RemoteException {
3470 synchronized (mDone) {
3471 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003472 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003473 mDone.set(true);
3474 mDone.notifyAll();
3475 }
3476 }
3477 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003478
3479 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3480 final AtomicBoolean mDone = new AtomicBoolean();
3481 int mResult;
3482
3483 public void reset() {
3484 synchronized (mDone) {
3485 mDone.set(false);
3486 }
3487 }
3488
3489 public void waitForCompletion() {
3490 synchronized (mDone) {
3491 while (mDone.get() == false) {
3492 try {
3493 mDone.wait();
3494 } catch (InterruptedException e) { }
3495 }
3496 }
3497 }
3498
3499 @Override
3500 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3501 synchronized (mDone) {
3502 mResult = returnCode;
3503 mDone.set(true);
3504 mDone.notifyAll();
3505 }
3506 }
3507 }
3508
Christopher Tate75a99702011-05-18 16:28:19 -07003509 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003510 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003511
3512 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3513 boolean okay = true;
3514
3515 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3516
3517 // The file content is an .apk file. Copy it out to a staging location and
3518 // attempt to install it.
3519 File apkFile = new File(mDataDir, info.packageName);
3520 try {
3521 FileOutputStream apkStream = new FileOutputStream(apkFile);
3522 byte[] buffer = new byte[32 * 1024];
3523 long size = info.size;
3524 while (size > 0) {
3525 long toRead = (buffer.length < size) ? buffer.length : size;
3526 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003527 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003528 apkStream.write(buffer, 0, didRead);
3529 size -= didRead;
3530 }
3531 apkStream.close();
3532
3533 // make sure the installer can read it
3534 apkFile.setReadable(true, false);
3535
3536 // Now install it
3537 Uri packageUri = Uri.fromFile(apkFile);
3538 mInstallObserver.reset();
3539 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003540 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3541 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003542 mInstallObserver.waitForCompletion();
3543
3544 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3545 // The only time we continue to accept install of data even if the
3546 // apk install failed is if we had already determined that we could
3547 // accept the data regardless.
3548 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3549 okay = false;
3550 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003551 } else {
3552 // Okay, the install succeeded. Make sure it was the right app.
3553 boolean uninstall = false;
3554 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3555 Slog.w(TAG, "Restore stream claimed to include apk for "
3556 + info.packageName + " but apk was really "
3557 + mInstallObserver.mPackageName);
3558 // delete the package we just put in place; it might be fraudulent
3559 okay = false;
3560 uninstall = true;
3561 } else {
3562 try {
3563 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3564 PackageManager.GET_SIGNATURES);
3565 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3566 Slog.w(TAG, "Restore stream contains apk of package "
3567 + info.packageName + " but it disallows backup/restore");
3568 okay = false;
3569 } else {
3570 // So far so good -- do the signatures match the manifest?
3571 Signature[] sigs = mManifestSignatures.get(info.packageName);
3572 if (!signaturesMatch(sigs, pkg)) {
3573 Slog.w(TAG, "Installed app " + info.packageName
3574 + " signatures do not match restore manifest");
3575 okay = false;
3576 uninstall = true;
3577 }
3578 }
3579 } catch (NameNotFoundException e) {
3580 Slog.w(TAG, "Install of package " + info.packageName
3581 + " succeeded but now not found");
3582 okay = false;
3583 }
3584 }
3585
3586 // If we're not okay at this point, we need to delete the package
3587 // that we just installed.
3588 if (uninstall) {
3589 mDeleteObserver.reset();
3590 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3591 mDeleteObserver, 0);
3592 mDeleteObserver.waitForCompletion();
3593 }
Christopher Tate75a99702011-05-18 16:28:19 -07003594 }
3595 } catch (IOException e) {
3596 Slog.e(TAG, "Unable to transcribe restored apk for install");
3597 okay = false;
3598 } finally {
3599 apkFile.delete();
3600 }
3601
3602 return okay;
3603 }
3604
3605 // Given an actual file content size, consume the post-content padding mandated
3606 // by the tar format.
3607 void skipTarPadding(long size, InputStream instream) throws IOException {
3608 long partial = (size + 512) % 512;
3609 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003610 final int needed = 512 - (int)partial;
3611 byte[] buffer = new byte[needed];
3612 if (readExactly(instream, buffer, 0, needed) == needed) {
3613 mBytes += needed;
3614 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003615 }
3616 }
3617
3618 // Returns a policy constant; takes a buffer arg to reduce memory churn
3619 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3620 throws IOException {
3621 // Fail on suspiciously large manifest files
3622 if (info.size > 64 * 1024) {
3623 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3624 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003625
Christopher Tate75a99702011-05-18 16:28:19 -07003626 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003627 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3628 mBytes += info.size;
3629 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003630
3631 RestorePolicy policy = RestorePolicy.IGNORE;
3632 String[] str = new String[1];
3633 int offset = 0;
3634
3635 try {
3636 offset = extractLine(buffer, offset, str);
3637 int version = Integer.parseInt(str[0]);
3638 if (version == BACKUP_MANIFEST_VERSION) {
3639 offset = extractLine(buffer, offset, str);
3640 String manifestPackage = str[0];
3641 // TODO: handle <original-package>
3642 if (manifestPackage.equals(info.packageName)) {
3643 offset = extractLine(buffer, offset, str);
3644 version = Integer.parseInt(str[0]); // app version
3645 offset = extractLine(buffer, offset, str);
3646 int platformVersion = Integer.parseInt(str[0]);
3647 offset = extractLine(buffer, offset, str);
3648 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3649 offset = extractLine(buffer, offset, str);
3650 boolean hasApk = str[0].equals("1");
3651 offset = extractLine(buffer, offset, str);
3652 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003653 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003654 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003655 for (int i = 0; i < numSigs; i++) {
3656 offset = extractLine(buffer, offset, str);
3657 sigs[i] = new Signature(str[0]);
3658 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003659 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003660
3661 // Okay, got the manifest info we need...
3662 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003663 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3664 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003665 // Fall through to IGNORE if the app explicitly disallows backup
3666 final int flags = pkgInfo.applicationInfo.flags;
3667 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3668 // Verify signatures against any installed version; if they
3669 // don't match, then we fall though and ignore the data. The
3670 // signatureMatch() method explicitly ignores the signature
3671 // check for packages installed on the system partition, because
3672 // such packages are signed with the platform cert instead of
3673 // the app developer's cert, so they're different on every
3674 // device.
3675 if (signaturesMatch(sigs, pkgInfo)) {
3676 if (pkgInfo.versionCode >= version) {
3677 Slog.i(TAG, "Sig + version match; taking data");
3678 policy = RestorePolicy.ACCEPT;
3679 } else {
3680 // The data is from a newer version of the app than
3681 // is presently installed. That means we can only
3682 // use it if the matching apk is also supplied.
3683 Slog.d(TAG, "Data version " + version
3684 + " is newer than installed version "
3685 + pkgInfo.versionCode + " - requiring apk");
3686 policy = RestorePolicy.ACCEPT_IF_APK;
3687 }
Christopher Tate75a99702011-05-18 16:28:19 -07003688 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003689 Slog.w(TAG, "Restore manifest signatures do not match "
3690 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003691 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003692 } else {
3693 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3694 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003695 }
3696 } catch (NameNotFoundException e) {
3697 // Okay, the target app isn't installed. We can process
3698 // the restore properly only if the dataset provides the
3699 // apk file and we can successfully install it.
3700 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3701 + " not installed; requiring apk in dataset");
3702 policy = RestorePolicy.ACCEPT_IF_APK;
3703 }
3704
3705 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3706 Slog.i(TAG, "Cannot restore package " + info.packageName
3707 + " without the matching .apk");
3708 }
3709 } else {
3710 Slog.i(TAG, "Missing signature on backed-up package "
3711 + info.packageName);
3712 }
3713 } else {
3714 Slog.i(TAG, "Expected package " + info.packageName
3715 + " but restore manifest claims " + manifestPackage);
3716 }
3717 } else {
3718 Slog.i(TAG, "Unknown restore manifest version " + version
3719 + " for package " + info.packageName);
3720 }
3721 } catch (NumberFormatException e) {
3722 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003723 } catch (IllegalArgumentException e) {
3724 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003725 }
3726
3727 return policy;
3728 }
3729
3730 // Builds a line from a byte buffer starting at 'offset', and returns
3731 // the index of the next unconsumed data in the buffer.
3732 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3733 final int end = buffer.length;
3734 if (offset >= end) throw new IOException("Incomplete data");
3735
3736 int pos;
3737 for (pos = offset; pos < end; pos++) {
3738 byte c = buffer[pos];
3739 // at LF we declare end of line, and return the next char as the
3740 // starting point for the next time through
3741 if (c == '\n') {
3742 break;
3743 }
3744 }
3745 outStr[0] = new String(buffer, offset, pos - offset);
3746 pos++; // may be pointing an extra byte past the end but that's okay
3747 return pos;
3748 }
3749
3750 void dumpFileMetadata(FileMetadata info) {
3751 if (DEBUG) {
3752 StringBuilder b = new StringBuilder(128);
3753
3754 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003755 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003756 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3757 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3758 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3759 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3760 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3761 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3762 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3763 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3764 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3765 b.append(String.format(" %9d ", info.size));
3766
3767 Date stamp = new Date(info.mtime);
3768 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3769
3770 b.append(info.packageName);
3771 b.append(" :: ");
3772 b.append(info.domain);
3773 b.append(" :: ");
3774 b.append(info.path);
3775
3776 Slog.i(TAG, b.toString());
3777 }
3778 }
3779 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3780 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3781 byte[] block = new byte[512];
3782 FileMetadata info = null;
3783
3784 boolean gotHeader = readTarHeader(instream, block);
3785 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003786 try {
3787 // okay, presume we're okay, and extract the various metadata
3788 info = new FileMetadata();
3789 info.size = extractRadix(block, 124, 12, 8);
3790 info.mtime = extractRadix(block, 136, 12, 8);
3791 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003792
Christopher Tate2efd2db2011-07-19 16:32:49 -07003793 info.path = extractString(block, 345, 155); // prefix
3794 String path = extractString(block, 0, 100);
3795 if (path.length() > 0) {
3796 if (info.path.length() > 0) info.path += '/';
3797 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003798 }
Christopher Tate75a99702011-05-18 16:28:19 -07003799
Christopher Tate2efd2db2011-07-19 16:32:49 -07003800 // tar link indicator field: 1 byte at offset 156 in the header.
3801 int typeChar = block[156];
3802 if (typeChar == 'x') {
3803 // pax extended header, so we need to read that
3804 gotHeader = readPaxExtendedHeader(instream, info);
3805 if (gotHeader) {
3806 // and after a pax extended header comes another real header -- read
3807 // that to find the real file type
3808 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003809 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003810 if (!gotHeader) throw new IOException("Bad or missing pax header");
3811
3812 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003813 }
Christopher Tate75a99702011-05-18 16:28:19 -07003814
Christopher Tate2efd2db2011-07-19 16:32:49 -07003815 switch (typeChar) {
3816 case '0': info.type = BackupAgent.TYPE_FILE; break;
3817 case '5': {
3818 info.type = BackupAgent.TYPE_DIRECTORY;
3819 if (info.size != 0) {
3820 Slog.w(TAG, "Directory entry with nonzero size in header");
3821 info.size = 0;
3822 }
3823 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003824 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003825 case 0: {
3826 // presume EOF
3827 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3828 return null;
3829 }
3830 default: {
3831 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3832 throw new IOException("Unknown entity type " + typeChar);
3833 }
Christopher Tate75a99702011-05-18 16:28:19 -07003834 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003835
3836 // Parse out the path
3837 //
3838 // first: apps/shared/unrecognized
3839 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3840 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3841 // File in shared storage. !!! TODO: implement this.
3842 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003843 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003844 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3845 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3846 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3847 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3848 // App content! Parse out the package name and domain
3849
3850 // strip the apps/ prefix
3851 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3852
3853 // extract the package name
3854 int slash = info.path.indexOf('/');
3855 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3856 info.packageName = info.path.substring(0, slash);
3857 info.path = info.path.substring(slash+1);
3858
3859 // if it's a manifest we're done, otherwise parse out the domains
3860 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3861 slash = info.path.indexOf('/');
3862 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3863 info.domain = info.path.substring(0, slash);
3864 // validate that it's one of the domains we understand
3865 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3866 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3867 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3868 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3869 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3870 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3871 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3872 throw new IOException("Unrecognized domain " + info.domain);
3873 }
3874
3875 info.path = info.path.substring(slash + 1);
3876 }
3877 }
3878 } catch (IOException e) {
3879 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003880 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003881 HEXLOG(block);
3882 }
3883 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003884 }
3885 }
3886 return info;
3887 }
3888
Christopher Tate2efd2db2011-07-19 16:32:49 -07003889 private void HEXLOG(byte[] block) {
3890 int offset = 0;
3891 int todo = block.length;
3892 StringBuilder buf = new StringBuilder(64);
3893 while (todo > 0) {
3894 buf.append(String.format("%04x ", offset));
3895 int numThisLine = (todo > 16) ? 16 : todo;
3896 for (int i = 0; i < numThisLine; i++) {
3897 buf.append(String.format("%02x ", block[offset+i]));
3898 }
3899 Slog.i("hexdump", buf.toString());
3900 buf.setLength(0);
3901 todo -= numThisLine;
3902 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003903 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003904 }
3905
Christopher Tate6853fcf2011-08-10 17:52:21 -07003906 // Read exactly the given number of bytes into a buffer at the stated offset.
3907 // Returns false if EOF is encountered before the requested number of bytes
3908 // could be read.
3909 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3910 throws IOException {
3911 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3912
3913 int soFar = 0;
3914 while (soFar < size) {
3915 int nRead = in.read(buffer, offset + soFar, size - soFar);
3916 if (nRead <= 0) {
3917 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3918 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003919 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003920 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003921 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003922 return soFar;
3923 }
3924
3925 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3926 final int got = readExactly(instream, block, 0, 512);
3927 if (got == 0) return false; // Clean EOF
3928 if (got < 512) throw new IOException("Unable to read full block header");
3929 mBytes += 512;
3930 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003931 }
3932
3933 // overwrites 'info' fields based on the pax extended header
3934 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3935 throws IOException {
3936 // We should never see a pax extended header larger than this
3937 if (info.size > 32*1024) {
3938 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3939 + " - aborting");
3940 throw new IOException("Sanity failure: pax header size " + info.size);
3941 }
3942
3943 // read whole blocks, not just the content size
3944 int numBlocks = (int)((info.size + 511) >> 9);
3945 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003946 if (readExactly(instream, data, 0, data.length) < data.length) {
3947 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003948 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003949 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003950
3951 final int contentSize = (int) info.size;
3952 int offset = 0;
3953 do {
3954 // extract the line at 'offset'
3955 int eol = offset+1;
3956 while (eol < contentSize && data[eol] != ' ') eol++;
3957 if (eol >= contentSize) {
3958 // error: we just hit EOD looking for the end of the size field
3959 throw new IOException("Invalid pax data");
3960 }
3961 // eol points to the space between the count and the key
3962 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3963 int key = eol + 1; // start of key=value
3964 eol = offset + linelen - 1; // trailing LF
3965 int value;
3966 for (value = key+1; data[value] != '=' && value <= eol; value++);
3967 if (value > eol) {
3968 throw new IOException("Invalid pax declaration");
3969 }
3970
3971 // pax requires that key/value strings be in UTF-8
3972 String keyStr = new String(data, key, value-key, "UTF-8");
3973 // -1 to strip the trailing LF
3974 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3975
3976 if ("path".equals(keyStr)) {
3977 info.path = valStr;
3978 } else if ("size".equals(keyStr)) {
3979 info.size = Long.parseLong(valStr);
3980 } else {
3981 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3982 }
3983
3984 offset += linelen;
3985 } while (offset < contentSize);
3986
3987 return true;
3988 }
3989
3990 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3991 throws IOException {
3992 long value = 0;
3993 final int end = offset + maxChars;
3994 for (int i = offset; i < end; i++) {
3995 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003996 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003997 if (b == 0 || b == ' ') break;
3998 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003999 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004000 }
4001 value = radix * value + (b - '0');
4002 }
4003 return value;
4004 }
4005
4006 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4007 final int end = offset + maxChars;
4008 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004009 // tar string fields terminate early with a NUL
4010 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004011 return new String(data, offset, eos-offset, "US-ASCII");
4012 }
4013
4014 void sendStartRestore() {
4015 if (mObserver != null) {
4016 try {
4017 mObserver.onStartRestore();
4018 } catch (RemoteException e) {
4019 Slog.w(TAG, "full restore observer went away: startRestore");
4020 mObserver = null;
4021 }
4022 }
4023 }
4024
4025 void sendOnRestorePackage(String name) {
4026 if (mObserver != null) {
4027 try {
4028 // TODO: use a more user-friendly name string
4029 mObserver.onRestorePackage(name);
4030 } catch (RemoteException e) {
4031 Slog.w(TAG, "full restore observer went away: restorePackage");
4032 mObserver = null;
4033 }
4034 }
4035 }
4036
4037 void sendEndRestore() {
4038 if (mObserver != null) {
4039 try {
4040 mObserver.onEndRestore();
4041 } catch (RemoteException e) {
4042 Slog.w(TAG, "full restore observer went away: endRestore");
4043 mObserver = null;
4044 }
4045 }
4046 }
4047 }
4048
Christopher Tatedf01dea2009-06-09 20:45:02 -07004049 // ----- Restore handling -----
4050
Christopher Tate78dd4a72009-11-04 11:49:08 -08004051 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4052 // If the target resides on the system partition, we allow it to restore
4053 // data from the like-named package in a restore set even if the signatures
4054 // do not match. (Unlike general applications, those flashed to the system
4055 // partition will be signed with the device's platform certificate, so on
4056 // different phones the same system app will have different signatures.)
4057 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004058 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004059 return true;
4060 }
4061
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004062 // Allow unsigned apps, but not signed on one device and unsigned on the other
4063 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004064 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004065 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004066 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004067 if ((storedSigs == null || storedSigs.length == 0)
4068 && (deviceSigs == null || deviceSigs.length == 0)) {
4069 return true;
4070 }
4071 if (storedSigs == null || deviceSigs == null) {
4072 return false;
4073 }
4074
Christopher Tateabce4e82009-06-18 18:35:32 -07004075 // !!! TODO: this demands that every stored signature match one
4076 // that is present on device, and does not demand the converse.
4077 // Is this this right policy?
4078 int nStored = storedSigs.length;
4079 int nDevice = deviceSigs.length;
4080
4081 for (int i=0; i < nStored; i++) {
4082 boolean match = false;
4083 for (int j=0; j < nDevice; j++) {
4084 if (storedSigs[i].equals(deviceSigs[j])) {
4085 match = true;
4086 break;
4087 }
4088 }
4089 if (!match) {
4090 return false;
4091 }
4092 }
4093 return true;
4094 }
4095
Christopher Tate2982d062011-09-06 20:35:24 -07004096 enum RestoreState {
4097 INITIAL,
4098 DOWNLOAD_DATA,
4099 PM_METADATA,
4100 RUNNING_QUEUE,
4101 FINAL
4102 }
4103
4104 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004105 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004106 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004107 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004108 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004109 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004110 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004111 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004112 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004113 private long mStartRealtime;
4114 private PackageManagerBackupAgent mPmAgent;
4115 private List<PackageInfo> mAgentPackages;
4116 private ArrayList<PackageInfo> mRestorePackages;
4117 private RestoreState mCurrentState;
4118 private int mCount;
4119 private boolean mFinished;
4120 private int mStatus;
4121 private File mBackupDataName;
4122 private File mNewStateName;
4123 private File mSavedStateName;
4124 private ParcelFileDescriptor mBackupData;
4125 private ParcelFileDescriptor mNewState;
4126 private PackageInfo mCurrentPackage;
4127
Christopher Tatedf01dea2009-06-09 20:45:02 -07004128
Christopher Tate5cbbf562009-06-22 16:44:51 -07004129 class RestoreRequest {
4130 public PackageInfo app;
4131 public int storedAppVersion;
4132
4133 RestoreRequest(PackageInfo _app, int _version) {
4134 app = _app;
4135 storedAppVersion = _version;
4136 }
4137 }
4138
Christopher Tate44a27902010-01-27 17:15:49 -08004139 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004140 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004141 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004142 mCurrentState = RestoreState.INITIAL;
4143 mFinished = false;
4144 mPmAgent = null;
4145
Christopher Tatedf01dea2009-06-09 20:45:02 -07004146 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004147 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004148 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004149 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004150 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004151 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004152
Christopher Tate284f1bb2011-07-07 14:31:18 -07004153 if (filterSet != null) {
4154 mFilterSet = new HashSet<String>();
4155 for (String pkg : filterSet) {
4156 mFilterSet.add(pkg);
4157 }
4158 } else {
4159 mFilterSet = null;
4160 }
4161
Christopher Tate5cb400b2009-06-25 16:03:14 -07004162 try {
4163 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4164 } catch (RemoteException e) {
4165 // can't happen; the transport is local
4166 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004167 }
4168
Christopher Tate2982d062011-09-06 20:35:24 -07004169 // Execute one tick of whatever state machine the task implements
4170 @Override
4171 public void execute() {
4172 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4173 switch (mCurrentState) {
4174 case INITIAL:
4175 beginRestore();
4176 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004177
Christopher Tate2982d062011-09-06 20:35:24 -07004178 case DOWNLOAD_DATA:
4179 downloadRestoreData();
4180 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004181
Christopher Tate2982d062011-09-06 20:35:24 -07004182 case PM_METADATA:
4183 restorePmMetadata();
4184 break;
4185
4186 case RUNNING_QUEUE:
4187 restoreNextAgent();
4188 break;
4189
4190 case FINAL:
4191 if (!mFinished) finalizeRestore();
4192 else {
4193 Slog.e(TAG, "Duplicate finish");
4194 }
4195 mFinished = true;
4196 break;
4197 }
4198 }
4199
4200 // Initialize and set up for the PM metadata restore, which comes first
4201 void beginRestore() {
4202 // Don't account time doing the restore as inactivity of the app
4203 // that has opened a restore session.
4204 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4205
4206 // Assume error until we successfully init everything
4207 mStatus = BackupConstants.TRANSPORT_ERROR;
4208
Christopher Tatedf01dea2009-06-09 20:45:02 -07004209 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004210 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004211 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004212
Dan Egnorefe52642009-06-24 00:16:33 -07004213 // Get the list of all packages which have backup enabled.
4214 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004215 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004216 PackageInfo omPackage = new PackageInfo();
4217 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004218 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004219
Christopher Tate2982d062011-09-06 20:35:24 -07004220 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004221 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004222 // if there's a filter set, strip out anything that isn't
4223 // present before proceeding
4224 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004225 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4226 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004227 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004228 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004229 }
4230 }
Christopher Tate2982d062011-09-06 20:35:24 -07004231 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004232 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004233 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004234 Slog.i(TAG, " " + p);
4235 }
4236 }
4237 }
Christopher Tate2982d062011-09-06 20:35:24 -07004238 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004239 } else {
4240 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004241 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004242 }
Dan Egnorefe52642009-06-24 00:16:33 -07004243
Christopher Tate7d562ec2009-06-25 18:03:43 -07004244 // let the observer know that we're running
4245 if (mObserver != null) {
4246 try {
4247 // !!! TODO: get an actual count from the transport after
4248 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004249 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004250 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004251 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004252 mObserver = null;
4253 }
4254 }
Christopher Tate2982d062011-09-06 20:35:24 -07004255 } catch (RemoteException e) {
4256 // Something has gone catastrophically wrong with the transport
4257 Slog.e(TAG, "Error communicating with transport for restore");
4258 executeNextState(RestoreState.FINAL);
4259 return;
4260 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004261
Christopher Tate2982d062011-09-06 20:35:24 -07004262 mStatus = BackupConstants.TRANSPORT_OK;
4263 executeNextState(RestoreState.DOWNLOAD_DATA);
4264 }
4265
4266 void downloadRestoreData() {
4267 // Note that the download phase can be very time consuming, but we're executing
4268 // it inline here on the looper. This is "okay" because it is not calling out to
4269 // third party code; the transport is "trusted," and so we assume it is being a
4270 // good citizen and timing out etc when appropriate.
4271 //
4272 // TODO: when appropriate, move the download off the looper and rearrange the
4273 // error handling around that.
4274 try {
4275 mStatus = mTransport.startRestore(mToken,
4276 mRestorePackages.toArray(new PackageInfo[0]));
4277 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004278 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004279 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004280 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004281 return;
4282 }
Christopher Tate2982d062011-09-06 20:35:24 -07004283 } catch (RemoteException e) {
4284 Slog.e(TAG, "Error communicating with transport for restore");
4285 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4286 mStatus = BackupConstants.TRANSPORT_ERROR;
4287 executeNextState(RestoreState.FINAL);
4288 return;
4289 }
Dan Egnorefe52642009-06-24 00:16:33 -07004290
Christopher Tate2982d062011-09-06 20:35:24 -07004291 // Successful download of the data to be parceled out to the apps, so off we go.
4292 executeNextState(RestoreState.PM_METADATA);
4293 }
4294
4295 void restorePmMetadata() {
4296 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004297 String packageName = mTransport.nextRestorePackage();
4298 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004299 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004300 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004301 mStatus = BackupConstants.TRANSPORT_ERROR;
4302 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004303 return;
4304 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004305 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004306 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004307 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004308 mStatus = BackupConstants.TRANSPORT_OK;
4309 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004310 return;
4311 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004312 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004313 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004314 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004315 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004316 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004317 return;
4318 }
4319
4320 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004321 PackageInfo omPackage = new PackageInfo();
4322 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4323 mPmAgent = new PackageManagerBackupAgent(
4324 mPackageManager, mAgentPackages);
4325 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004326 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004327 // The PM agent called operationComplete() already, because our invocation
4328 // of it is process-local and therefore synchronous. That means that a
4329 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4330 // proceed with running the queue do we remove that pending message and
4331 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004332
Christopher Tate8c032472009-07-02 14:28:47 -07004333 // Verify that the backup set includes metadata. If not, we can't do
4334 // signature/version verification etc, so we simply do not proceed with
4335 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004336 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004337 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004338 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004339 "Package manager restore metadata missing");
4340 mStatus = BackupConstants.TRANSPORT_ERROR;
4341 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4342 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004343 return;
4344 }
Christopher Tate2982d062011-09-06 20:35:24 -07004345 } catch (RemoteException e) {
4346 Slog.e(TAG, "Error communicating with transport for restore");
4347 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4348 mStatus = BackupConstants.TRANSPORT_ERROR;
4349 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4350 executeNextState(RestoreState.FINAL);
4351 return;
4352 }
Christopher Tate8c032472009-07-02 14:28:47 -07004353
Christopher Tate2982d062011-09-06 20:35:24 -07004354 // Metadata is intact, so we can now run the restore queue. If we get here,
4355 // we have already enqueued the necessary next-step message on the looper.
4356 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004357
Christopher Tate2982d062011-09-06 20:35:24 -07004358 void restoreNextAgent() {
4359 try {
4360 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004361
Christopher Tate2982d062011-09-06 20:35:24 -07004362 if (packageName == null) {
4363 Slog.e(TAG, "Error getting next restore package");
4364 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4365 executeNextState(RestoreState.FINAL);
4366 return;
4367 } else if (packageName.equals("")) {
4368 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4369 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4370 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4371 executeNextState(RestoreState.FINAL);
4372 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004373 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004374
4375 if (mObserver != null) {
4376 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004377 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004378 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004379 Slog.d(TAG, "Restore observer died in onUpdate");
4380 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004381 }
4382 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004383
Christopher Tate2982d062011-09-06 20:35:24 -07004384 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4385 if (metaInfo == null) {
4386 Slog.e(TAG, "Missing metadata for " + packageName);
4387 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4388 "Package metadata missing");
4389 executeNextState(RestoreState.RUNNING_QUEUE);
4390 return;
Christopher Tate84725812010-02-04 15:52:40 -08004391 }
4392
Christopher Tate2982d062011-09-06 20:35:24 -07004393 PackageInfo packageInfo;
4394 try {
4395 int flags = PackageManager.GET_SIGNATURES;
4396 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4397 } catch (NameNotFoundException e) {
4398 Slog.e(TAG, "Invalid package restoring data", e);
4399 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4400 "Package missing on device");
4401 executeNextState(RestoreState.RUNNING_QUEUE);
4402 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004403 }
4404
Christopher Tate2982d062011-09-06 20:35:24 -07004405 if (metaInfo.versionCode > packageInfo.versionCode) {
4406 // Data is from a "newer" version of the app than we have currently
4407 // installed. If the app has not declared that it is prepared to
4408 // handle this case, we do not attempt the restore.
4409 if ((packageInfo.applicationInfo.flags
4410 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4411 String message = "Version " + metaInfo.versionCode
4412 + " > installed version " + packageInfo.versionCode;
4413 Slog.w(TAG, "Package " + packageName + ": " + message);
4414 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4415 packageName, message);
4416 executeNextState(RestoreState.RUNNING_QUEUE);
4417 return;
4418 } else {
4419 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4420 + " > installed " + packageInfo.versionCode
4421 + " but restoreAnyVersion");
4422 }
4423 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004424
Christopher Tate2982d062011-09-06 20:35:24 -07004425 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4426 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4427 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4428 "Signature mismatch");
4429 executeNextState(RestoreState.RUNNING_QUEUE);
4430 return;
4431 }
4432
4433 if (DEBUG) Slog.v(TAG, "Package " + packageName
4434 + " restore version [" + metaInfo.versionCode
4435 + "] is compatible with installed version ["
4436 + packageInfo.versionCode + "]");
4437
4438 // Then set up and bind the agent
4439 IBackupAgent agent = bindToAgentSynchronous(
4440 packageInfo.applicationInfo,
4441 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4442 if (agent == null) {
4443 Slog.w(TAG, "Can't find backup agent for " + packageName);
4444 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4445 "Restore agent missing");
4446 executeNextState(RestoreState.RUNNING_QUEUE);
4447 return;
4448 }
4449
4450 // And then finally start the restore on this agent
4451 try {
4452 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4453 ++mCount;
4454 } catch (Exception e) {
4455 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4456 agentErrorCleanup();
4457 executeNextState(RestoreState.RUNNING_QUEUE);
4458 }
4459 } catch (RemoteException e) {
4460 Slog.e(TAG, "Unable to fetch restore data from transport");
4461 mStatus = BackupConstants.TRANSPORT_ERROR;
4462 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004463 }
4464 }
4465
Christopher Tate2982d062011-09-06 20:35:24 -07004466 void finalizeRestore() {
4467 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4468
4469 try {
4470 mTransport.finishRestore();
4471 } catch (RemoteException e) {
4472 Slog.e(TAG, "Error finishing restore", e);
4473 }
4474
4475 if (mObserver != null) {
4476 try {
4477 mObserver.restoreFinished(mStatus);
4478 } catch (RemoteException e) {
4479 Slog.d(TAG, "Restore observer died at restoreFinished");
4480 }
4481 }
4482
4483 // If this was a restoreAll operation, record that this was our
4484 // ancestral dataset, as well as the set of apps that are possibly
4485 // restoreable from the dataset
4486 if (mTargetPackage == null && mPmAgent != null) {
4487 mAncestralPackages = mPmAgent.getRestoredPackages();
4488 mAncestralToken = mToken;
4489 writeRestoreTokens();
4490 }
4491
4492 // We must under all circumstances tell the Package Manager to
4493 // proceed with install notifications if it's waiting for us.
4494 if (mPmToken > 0) {
4495 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4496 try {
4497 mPackageManagerBinder.finishPackageInstall(mPmToken);
4498 } catch (RemoteException e) { /* can't happen */ }
4499 }
4500
4501 // Furthermore we need to reset the session timeout clock
4502 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4503 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4504 TIMEOUT_RESTORE_INTERVAL);
4505
4506 // done; we can finally release the wakelock
4507 Slog.i(TAG, "Restore complete.");
4508 mWakelock.release();
4509 }
4510
4511 // Call asynchronously into the app, passing it the restore data. The next step
4512 // after this is always a callback, either operationComplete() or handleTimeout().
4513 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004514 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004515 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004516 final String packageName = app.packageName;
4517
Christopher Tate2982d062011-09-06 20:35:24 -07004518 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004519
Christopher Tatec7b31e32009-06-10 15:49:30 -07004520 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004521 mBackupDataName = new File(mDataDir, packageName + ".restore");
4522 mNewStateName = new File(mStateDir, packageName + ".new");
4523 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004524
Christopher Tate4a627c72011-04-01 14:43:32 -07004525 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004526 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004527 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004528 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004529 ParcelFileDescriptor.MODE_READ_WRITE |
4530 ParcelFileDescriptor.MODE_CREATE |
4531 ParcelFileDescriptor.MODE_TRUNCATE);
4532
Christopher Tate2982d062011-09-06 20:35:24 -07004533 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004534 // Transport-level failure, so we wind everything up and
4535 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004536 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004537 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004538 mBackupData.close();
4539 mBackupDataName.delete();
4540 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004541 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004542 }
4543
4544 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004545 mBackupData.close();
4546 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004547 ParcelFileDescriptor.MODE_READ_ONLY);
4548
Christopher Tate2982d062011-09-06 20:35:24 -07004549 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004550 ParcelFileDescriptor.MODE_READ_WRITE |
4551 ParcelFileDescriptor.MODE_CREATE |
4552 ParcelFileDescriptor.MODE_TRUNCATE);
4553
Christopher Tate44a27902010-01-27 17:15:49 -08004554 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004555 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4556 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004557 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004558 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004559 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004560 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004561
Christopher Tate2982d062011-09-06 20:35:24 -07004562 // After a restore failure we go back to running the queue. If there
4563 // are no more packages to be restored that will be handled by the
4564 // next step.
4565 executeNextState(RestoreState.RUNNING_QUEUE);
4566 }
4567 }
Chris Tate249345b2010-10-29 12:57:04 -07004568
Christopher Tate2982d062011-09-06 20:35:24 -07004569 void agentErrorCleanup() {
4570 // If the agent fails restore, it might have put the app's data
4571 // into an incoherent state. For consistency we wipe its data
4572 // again in this case before continuing with normal teardown
4573 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4574 agentCleanup();
4575 }
4576
4577 void agentCleanup() {
4578 mBackupDataName.delete();
4579 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4580 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4581 mBackupData = mNewState = null;
4582
4583 // if everything went okay, remember the recorded state now
4584 //
4585 // !!! TODO: the restored data should be migrated on the server
4586 // side into the current dataset. In that case the new state file
4587 // we just created would reflect the data already extant in the
4588 // backend, so there'd be nothing more to do. Until that happens,
4589 // however, we need to make sure that we record the data to the
4590 // current backend dataset. (Yes, this means shipping the data over
4591 // the wire in both directions. That's bad, but consistency comes
4592 // first, then efficiency.) Once we introduce server-side data
4593 // migration to the newly-restored device's dataset, we will change
4594 // the following from a discard of the newly-written state to the
4595 // "correct" operation of renaming into the canonical state blob.
4596 mNewStateName.delete(); // TODO: remove; see above comment
4597 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4598
4599 // If this wasn't the PM pseudopackage, tear down the agent side
4600 if (mCurrentPackage.applicationInfo != null) {
4601 // unbind and tidy up even on timeout or failure
4602 try {
4603 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4604
4605 // The agent was probably running with a stub Application object,
4606 // which isn't a valid run mode for the main app logic. Shut
4607 // down the app so that next time it's launched, it gets the
4608 // usual full initialization. Note that this is only done for
4609 // full-system restores: when a single app has requested a restore,
4610 // it is explicitly not killed following that operation.
4611 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4612 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4613 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4614 + mCurrentPackage.applicationInfo.processName);
4615 mActivityManager.killApplicationProcess(
4616 mCurrentPackage.applicationInfo.processName,
4617 mCurrentPackage.applicationInfo.uid);
4618 }
4619 } catch (RemoteException e) {
4620 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004621 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004622 }
Christopher Tate2982d062011-09-06 20:35:24 -07004623
4624 // The caller is responsible for reestablishing the state machine; our
4625 // responsibility here is to clear the decks for whatever comes next.
4626 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4627 synchronized (mCurrentOpLock) {
4628 mCurrentOperations.clear();
4629 }
4630 }
4631
4632 // A call to agent.doRestore() has been positively acknowledged as complete
4633 @Override
4634 public void operationComplete() {
4635 int size = (int) mBackupDataName.length();
4636 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4637 // Just go back to running the restore queue
4638 agentCleanup();
4639
4640 executeNextState(RestoreState.RUNNING_QUEUE);
4641 }
4642
4643 // A call to agent.doRestore() has timed out
4644 @Override
4645 public void handleTimeout() {
4646 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4647 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4648 mCurrentPackage.packageName, "restore timeout");
4649 // Handle like an agent that threw on invocation: wipe it and go on to the next
4650 agentErrorCleanup();
4651 executeNextState(RestoreState.RUNNING_QUEUE);
4652 }
4653
4654 void executeNextState(RestoreState nextState) {
4655 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4656 + this + " nextState=" + nextState);
4657 mCurrentState = nextState;
4658 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4659 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004660 }
4661 }
4662
Christopher Tate44a27902010-01-27 17:15:49 -08004663 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004664 IBackupTransport mTransport;
4665 PackageInfo mPackage;
4666
Christopher Tate44a27902010-01-27 17:15:49 -08004667 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004668 mTransport = transport;
4669 mPackage = packageInfo;
4670 }
4671
Christopher Tateee0e78a2009-07-02 11:17:03 -07004672 public void run() {
4673 try {
4674 // Clear the on-device backup state to ensure a full backup next time
4675 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4676 File stateFile = new File(stateDir, mPackage.packageName);
4677 stateFile.delete();
4678
4679 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004680 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004681 mTransport.clearBackupData(mPackage);
4682 } catch (RemoteException e) {
4683 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004684 } catch (Exception e) {
4685 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004686 } finally {
4687 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004688 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004689 mTransport.finishBackup();
4690 } catch (RemoteException e) {
4691 // can't happen; the transport is local
4692 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004693
4694 // Last but not least, release the cpu
4695 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004696 }
4697 }
4698 }
4699
Christopher Tate44a27902010-01-27 17:15:49 -08004700 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004701 HashSet<String> mQueue;
4702
Christopher Tate44a27902010-01-27 17:15:49 -08004703 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004704 mQueue = transportNames;
4705 }
4706
Christopher Tate4cc86e12009-09-21 19:36:51 -07004707 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004708 try {
4709 for (String transportName : mQueue) {
4710 IBackupTransport transport = getTransport(transportName);
4711 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004712 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004713 continue;
4714 }
4715
Joe Onorato8a9b2202010-02-26 18:56:32 -08004716 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004717 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004718 long startRealtime = SystemClock.elapsedRealtime();
4719 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004720
Christopher Tate4cc86e12009-09-21 19:36:51 -07004721 if (status == BackupConstants.TRANSPORT_OK) {
4722 status = transport.finishBackup();
4723 }
4724
4725 // Okay, the wipe really happened. Clean up our local bookkeeping.
4726 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004727 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004728 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004729 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004730 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004731 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004732 synchronized (mQueueLock) {
4733 recordInitPendingLocked(false, transportName);
4734 }
Dan Egnor726247c2009-09-29 19:12:31 -07004735 } else {
4736 // If this didn't work, requeue this one and try again
4737 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004738 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004739 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004740 synchronized (mQueueLock) {
4741 recordInitPendingLocked(true, transportName);
4742 }
4743 // do this via another alarm to make sure of the wakelock states
4744 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004745 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004746 + transportName + " resched in " + delay);
4747 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4748 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004749 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004750 }
4751 } catch (RemoteException e) {
4752 // can't happen; the transports are local
4753 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004754 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004755 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004756 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004757 mWakelock.release();
4758 }
4759 }
4760 }
4761
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004762 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004763 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004764 dataChangedImpl(packageName, targets);
4765 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004766
Christopher Tatea3d55342012-03-27 13:16:18 -07004767 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004768 // Record that we need a backup pass for the caller. Since multiple callers
4769 // may share a uid, we need to note all candidates within that uid and schedule
4770 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004771 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004772
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004773 if (targets == null) {
4774 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4775 + " uid=" + Binder.getCallingUid());
4776 return;
4777 }
4778
4779 synchronized (mQueueLock) {
4780 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004781 if (targets.contains(packageName)) {
4782 // Add the caller to the set of pending backups. If there is
4783 // one already there, then overwrite it, but no harm done.
4784 BackupRequest req = new BackupRequest(packageName);
4785 if (mPendingBackups.put(packageName, req) == null) {
4786 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004787
Christopher Tatea3d55342012-03-27 13:16:18 -07004788 // Journal this request in case of crash. The put()
4789 // operation returned null when this package was not already
4790 // in the set; we want to avoid touching the disk redundantly.
4791 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004792
Christopher Tatea3d55342012-03-27 13:16:18 -07004793 if (MORE_DEBUG) {
4794 int numKeys = mPendingBackups.size();
4795 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4796 for (BackupRequest b : mPendingBackups.values()) {
4797 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004798 }
4799 }
4800 }
4801 }
4802 }
4803 }
4804
4805 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004806 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004807 // If the caller does not hold the BACKUP permission, it can only request a
4808 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004809 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004810 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004811 synchronized (mBackupParticipants) {
4812 return mBackupParticipants.get(Binder.getCallingUid());
4813 }
4814 }
4815
4816 // a caller with full permission can ask to back up any participating app
4817 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004818 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004819 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004820 int N = mBackupParticipants.size();
4821 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004822 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004823 if (s != null) {
4824 targets.addAll(s);
4825 }
4826 }
4827 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004828 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004829 }
Christopher Tate46758122009-05-06 11:22:00 -07004830
Christopher Tatecde87f42009-06-12 12:55:53 -07004831 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004832 RandomAccessFile out = null;
4833 try {
4834 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4835 out = new RandomAccessFile(mJournal, "rws");
4836 out.seek(out.length());
4837 out.writeUTF(str);
4838 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004839 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004840 mJournal = null;
4841 } finally {
4842 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004843 }
4844 }
4845
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004846 // ----- IBackupManager binder interface -----
4847
4848 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004849 final int callingUserHandle = UserHandle.getCallingUserId();
4850 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004851 // App is running under a non-owner user profile. For now, we do not back
4852 // up data from secondary user profiles.
4853 // TODO: backups for all user profiles.
4854 if (MORE_DEBUG) {
4855 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4856 + callingUserHandle);
4857 }
4858 return;
4859 }
4860
Christopher Tatea3d55342012-03-27 13:16:18 -07004861 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004862 if (targets == null) {
4863 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4864 + " uid=" + Binder.getCallingUid());
4865 return;
4866 }
4867
4868 mBackupHandler.post(new Runnable() {
4869 public void run() {
4870 dataChangedImpl(packageName, targets);
4871 }
4872 });
4873 }
4874
Christopher Tateee0e78a2009-07-02 11:17:03 -07004875 // Clear the given package's backup data from the current transport
4876 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004877 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004878 PackageInfo info;
4879 try {
4880 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4881 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004882 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004883 return;
4884 }
4885
4886 // If the caller does not hold the BACKUP permission, it can only request a
4887 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004888 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004889 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004890 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4891 apps = mBackupParticipants.get(Binder.getCallingUid());
4892 } else {
4893 // a caller with full permission can ask to back up any participating app
4894 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004895 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004896 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004897 int N = mBackupParticipants.size();
4898 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004899 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004900 if (s != null) {
4901 apps.addAll(s);
4902 }
4903 }
4904 }
4905
Christopher Tatea3d55342012-03-27 13:16:18 -07004906 // Is the given app an available participant?
4907 if (apps.contains(packageName)) {
4908 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4909 // found it; fire off the clear request
4910 synchronized (mQueueLock) {
4911 long oldId = Binder.clearCallingIdentity();
4912 mWakelock.acquire();
4913 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4914 new ClearParams(getTransport(mCurrentTransport), info));
4915 mBackupHandler.sendMessage(msg);
4916 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004917 }
4918 }
4919 }
4920
Christopher Tateace7f092009-06-15 18:07:25 -07004921 // Run a backup pass immediately for any applications that have declared
4922 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004923 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004925
Joe Onorato8a9b2202010-02-26 18:56:32 -08004926 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004927 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004928 // Because the alarms we are using can jitter, and we want an *immediate*
4929 // backup pass to happen, we restart the timer beginning with "next time,"
4930 // then manually fire the backup trigger intent ourselves.
4931 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004932 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004933 mRunBackupIntent.send();
4934 } catch (PendingIntent.CanceledException e) {
4935 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004936 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004937 }
Christopher Tate46758122009-05-06 11:22:00 -07004938 }
4939 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004940
Christopher Tated2c0cd42011-09-15 15:51:29 -07004941 boolean deviceIsProvisioned() {
4942 final ContentResolver resolver = mContext.getContentResolver();
4943 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4944 }
4945
Christopher Tate4a627c72011-04-01 14:43:32 -07004946 // Run a *full* backup pass for the given package, writing the resulting data stream
4947 // to the supplied file descriptor. This method is synchronous and does not return
4948 // to the caller until the backup has been completed.
4949 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004950 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004951 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4952
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004953 final int callingUserHandle = UserHandle.getCallingUserId();
4954 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004955 throw new IllegalStateException("Backup supported only for the device owner");
4956 }
4957
Christopher Tate4a627c72011-04-01 14:43:32 -07004958 // Validate
4959 if (!doAllApps) {
4960 if (!includeShared) {
4961 // If we're backing up shared data (sdcard or equivalent), then we can run
4962 // without any supplied app names. Otherwise, we'd be doing no work, so
4963 // report the error.
4964 if (pkgList == null || pkgList.length == 0) {
4965 throw new IllegalArgumentException(
4966 "Backup requested but neither shared nor any apps named");
4967 }
4968 }
4969 }
4970
Christopher Tate4a627c72011-04-01 14:43:32 -07004971 long oldId = Binder.clearCallingIdentity();
4972 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004973 // Doesn't make sense to do a full backup prior to setup
4974 if (!deviceIsProvisioned()) {
4975 Slog.i(TAG, "Full backup not supported before setup");
4976 return;
4977 }
4978
4979 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4980 + " shared=" + includeShared + " all=" + doAllApps
4981 + " pkgs=" + pkgList);
4982 Slog.i(TAG, "Beginning full backup...");
4983
Christopher Tate4a627c72011-04-01 14:43:32 -07004984 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004985 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004986 final int token = generateToken();
4987 synchronized (mFullConfirmations) {
4988 mFullConfirmations.put(token, params);
4989 }
4990
Christopher Tate75a99702011-05-18 16:28:19 -07004991 // start up the confirmation UI
4992 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4993 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4994 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004995 mFullConfirmations.delete(token);
4996 return;
4997 }
Christopher Tate75a99702011-05-18 16:28:19 -07004998
4999 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005000 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5001
5002 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005003 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005004
5005 // wait for the backup to be performed
5006 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5007 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005008 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005009 try {
5010 fd.close();
5011 } catch (IOException e) {
5012 // just eat it
5013 }
Christopher Tate75a99702011-05-18 16:28:19 -07005014 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005015 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005016 }
Christopher Tate75a99702011-05-18 16:28:19 -07005017 }
5018
5019 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005020 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005021
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005022 final int callingUserHandle = UserHandle.getCallingUserId();
5023 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005024 throw new IllegalStateException("Restore supported only for the device owner");
5025 }
5026
Christopher Tate75a99702011-05-18 16:28:19 -07005027 long oldId = Binder.clearCallingIdentity();
5028
5029 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005030 // Check whether the device has been provisioned -- we don't handle
5031 // full restores prior to completing the setup process.
5032 if (!deviceIsProvisioned()) {
5033 Slog.i(TAG, "Full restore not permitted before setup");
5034 return;
5035 }
5036
5037 Slog.i(TAG, "Beginning full restore...");
5038
Christopher Tate75a99702011-05-18 16:28:19 -07005039 FullRestoreParams params = new FullRestoreParams(fd);
5040 final int token = generateToken();
5041 synchronized (mFullConfirmations) {
5042 mFullConfirmations.put(token, params);
5043 }
5044
5045 // start up the confirmation UI
5046 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5047 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5048 Slog.e(TAG, "Unable to launch full restore confirmation");
5049 mFullConfirmations.delete(token);
5050 return;
5051 }
5052
5053 // make sure the screen is lit for the user interaction
5054 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5055
5056 // start the confirmation countdown
5057 startConfirmationTimeout(token, params);
5058
5059 // wait for the restore to be performed
5060 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5061 waitForCompletion(params);
5062 } finally {
5063 try {
5064 fd.close();
5065 } catch (IOException e) {
5066 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5067 }
5068 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005069 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005070 }
5071 }
5072
5073 boolean startConfirmationUi(int token, String action) {
5074 try {
5075 Intent confIntent = new Intent(action);
5076 confIntent.setClassName("com.android.backupconfirm",
5077 "com.android.backupconfirm.BackupRestoreConfirmation");
5078 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5079 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5080 mContext.startActivity(confIntent);
5081 } catch (ActivityNotFoundException e) {
5082 return false;
5083 }
5084 return true;
5085 }
5086
5087 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005088 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005089 + TIMEOUT_FULL_CONFIRMATION + " millis");
5090 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5091 token, 0, params);
5092 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005093 }
5094
5095 void waitForCompletion(FullParams params) {
5096 synchronized (params.latch) {
5097 while (params.latch.get() == false) {
5098 try {
5099 params.latch.wait();
5100 } catch (InterruptedException e) { /* never interrupted */ }
5101 }
5102 }
5103 }
5104
5105 void signalFullBackupRestoreCompletion(FullParams params) {
5106 synchronized (params.latch) {
5107 params.latch.set(true);
5108 params.latch.notifyAll();
5109 }
5110 }
5111
5112 // Confirm that the previously-requested full backup/restore operation can proceed. This
5113 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005114 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005115 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005116 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005117 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5118 + " allow=" + allow);
5119
5120 // TODO: possibly require not just this signature-only permission, but even
5121 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005122 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005123
5124 long oldId = Binder.clearCallingIdentity();
5125 try {
5126
5127 FullParams params;
5128 synchronized (mFullConfirmations) {
5129 params = mFullConfirmations.get(token);
5130 if (params != null) {
5131 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5132 mFullConfirmations.delete(token);
5133
5134 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005135 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005136 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005137 : MSG_RUN_FULL_RESTORE;
5138
Christopher Tate728a1c42011-07-28 18:03:03 -07005139 params.observer = observer;
5140 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005141
5142 boolean isEncrypted;
5143 try {
5144 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5145 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5146 } catch (RemoteException e) {
5147 // couldn't contact the mount service; fail "safe" and assume encryption
5148 Slog.e(TAG, "Unable to contact mount service!");
5149 isEncrypted = true;
5150 }
5151 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005152
Christopher Tate75a99702011-05-18 16:28:19 -07005153 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005154 mWakelock.acquire();
5155 Message msg = mBackupHandler.obtainMessage(verb, params);
5156 mBackupHandler.sendMessage(msg);
5157 } else {
5158 Slog.w(TAG, "User rejected full backup/restore operation");
5159 // indicate completion without having actually transferred any data
5160 signalFullBackupRestoreCompletion(params);
5161 }
5162 } else {
5163 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5164 }
5165 }
5166 } finally {
5167 Binder.restoreCallingIdentity(oldId);
5168 }
5169 }
5170
Christopher Tate8031a3d2009-07-06 16:36:05 -07005171 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005172 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005173 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005174 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005175
Joe Onorato8a9b2202010-02-26 18:56:32 -08005176 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005177
Christopher Tate6ef58a12009-06-29 14:56:28 -07005178 boolean wasEnabled = mEnabled;
5179 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005180 Settings.Secure.putInt(mContext.getContentResolver(),
5181 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005182 mEnabled = enable;
5183 }
5184
Christopher Tate49401dd2009-07-01 12:34:29 -07005185 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005186 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005187 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005188 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005189 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005190 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005191 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005192
Christopher Tateb6787f22009-07-02 17:40:45 -07005193 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005194
5195 // This also constitutes an opt-out, so we wipe any data for
5196 // this device from the backend. We start that process with
5197 // an alarm in order to guarantee wakelock states.
5198 if (wasEnabled && mProvisioned) {
5199 // NOTE: we currently flush every registered transport, not just
5200 // the currently-active one.
5201 HashSet<String> allTransports;
5202 synchronized (mTransports) {
5203 allTransports = new HashSet<String>(mTransports.keySet());
5204 }
5205 // build the set of transports for which we are posting an init
5206 for (String transport : allTransports) {
5207 recordInitPendingLocked(true, transport);
5208 }
5209 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5210 mRunInitIntent);
5211 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005212 }
5213 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005214 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005215
Christopher Tatecce9da52010-02-03 15:11:15 -08005216 // Enable/disable automatic restore of app data at install time
5217 public void setAutoRestore(boolean doAutoRestore) {
5218 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005219 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005220
Joe Onorato8a9b2202010-02-26 18:56:32 -08005221 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005222
5223 synchronized (this) {
5224 Settings.Secure.putInt(mContext.getContentResolver(),
5225 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5226 mAutoRestore = doAutoRestore;
5227 }
5228 }
5229
Christopher Tate8031a3d2009-07-06 16:36:05 -07005230 // Mark the backup service as having been provisioned
5231 public void setBackupProvisioned(boolean available) {
5232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5233 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005234 /*
5235 * This is now a no-op; provisioning is simply the device's own setup state.
5236 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005237 }
5238
5239 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005240 // We used to use setInexactRepeating(), but that may be linked to
5241 // backups running at :00 more often than not, creating load spikes.
5242 // Schedule at an exact time for now, and also add a bit of "fuzz".
5243
5244 Random random = new Random();
5245 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5246 random.nextInt(FUZZ_MILLIS);
5247 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5248 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005249 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005250 }
5251
Christopher Tate6ef58a12009-06-29 14:56:28 -07005252 // Report whether the backup mechanism is currently enabled
5253 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005254 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005255 return mEnabled; // no need to synchronize just to read it
5256 }
5257
Christopher Tate91717492009-06-26 21:07:13 -07005258 // Report the name of the currently active transport
5259 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005261 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005262 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005263 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005264 }
5265
Christopher Tate91717492009-06-26 21:07:13 -07005266 // Report all known, available backup transports
5267 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005269
Christopher Tate91717492009-06-26 21:07:13 -07005270 String[] list = null;
5271 ArrayList<String> known = new ArrayList<String>();
5272 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5273 if (entry.getValue() != null) {
5274 known.add(entry.getKey());
5275 }
5276 }
5277
5278 if (known.size() > 0) {
5279 list = new String[known.size()];
5280 known.toArray(list);
5281 }
5282 return list;
5283 }
5284
5285 // Select which transport to use for the next backup operation. If the given
5286 // name is not one of the available transports, no action is taken and the method
5287 // returns null.
5288 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005290
5291 synchronized (mTransports) {
5292 String prevTransport = null;
5293 if (mTransports.get(transport) != null) {
5294 prevTransport = mCurrentTransport;
5295 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005296 Settings.Secure.putString(mContext.getContentResolver(),
5297 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005298 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005299 + " returning " + prevTransport);
5300 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005301 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005302 }
5303 return prevTransport;
5304 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005305 }
5306
Christopher Tatef5e1c292010-12-08 18:40:26 -08005307 // Supply the configuration Intent for the given transport. If the name is not one
5308 // of the available transports, or if the transport does not supply any configuration
5309 // UI, the method returns null.
5310 public Intent getConfigurationIntent(String transportName) {
5311 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5312 "getConfigurationIntent");
5313
5314 synchronized (mTransports) {
5315 final IBackupTransport transport = mTransports.get(transportName);
5316 if (transport != null) {
5317 try {
5318 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005319 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005320 + intent);
5321 return intent;
5322 } catch (RemoteException e) {
5323 /* fall through to return null */
5324 }
5325 }
5326 }
5327
5328 return null;
5329 }
5330
5331 // Supply the configuration summary string for the given transport. If the name is
5332 // not one of the available transports, or if the transport does not supply any
5333 // summary / destination string, the method can return null.
5334 //
5335 // This string is used VERBATIM as the summary text of the relevant Settings item!
5336 public String getDestinationString(String transportName) {
5337 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005338 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005339
5340 synchronized (mTransports) {
5341 final IBackupTransport transport = mTransports.get(transportName);
5342 if (transport != null) {
5343 try {
5344 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005345 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005346 return text;
5347 } catch (RemoteException e) {
5348 /* fall through to return null */
5349 }
5350 }
5351 }
5352
5353 return null;
5354 }
5355
Christopher Tate043dadc2009-06-02 16:11:00 -07005356 // Callback: a requested backup agent has been instantiated. This should only
5357 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005358 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005359 synchronized(mAgentConnectLock) {
5360 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005361 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005362 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5363 mConnectedAgent = agent;
5364 mConnecting = false;
5365 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005366 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005367 + " claiming agent connected");
5368 }
5369 mAgentConnectLock.notifyAll();
5370 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005371 }
5372
5373 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5374 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005375 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005376 public void agentDisconnected(String packageName) {
5377 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005378 synchronized(mAgentConnectLock) {
5379 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5380 mConnectedAgent = null;
5381 mConnecting = false;
5382 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005383 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005384 + " claiming agent disconnected");
5385 }
5386 mAgentConnectLock.notifyAll();
5387 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005388 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005389
Christopher Tate1bb69062010-02-19 17:02:12 -08005390 // An application being installed will need a restore pass, then the Package Manager
5391 // will need to be told when the restore is finished.
5392 public void restoreAtInstall(String packageName, int token) {
5393 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005394 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005395 + " attemping install-time restore");
5396 return;
5397 }
5398
5399 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005401 + " token=" + Integer.toHexString(token));
5402
Christopher Tatef0872722010-02-25 15:22:48 -08005403 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005404 // okay, we're going to attempt a restore of this package from this restore set.
5405 // The eventual message back into the Package Manager to run the post-install
5406 // steps for 'token' will be issued from the restore handling code.
5407
5408 // We can use a synthetic PackageInfo here because:
5409 // 1. We know it's valid, since the Package Manager supplied the name
5410 // 2. Only the packageName field will be used by the restore code
5411 PackageInfo pkg = new PackageInfo();
5412 pkg.packageName = packageName;
5413
5414 mWakelock.acquire();
5415 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5416 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005417 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005418 mBackupHandler.sendMessage(msg);
5419 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005420 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5421 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005422 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005423 try {
5424 mPackageManagerBinder.finishPackageInstall(token);
5425 } catch (RemoteException e) { /* can't happen */ }
5426 }
5427 }
5428
Christopher Tate8c850b72009-06-07 19:33:20 -07005429 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005430 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5431 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5432 + " transport=" + transport);
5433
5434 boolean needPermission = true;
5435 if (transport == null) {
5436 transport = mCurrentTransport;
5437
5438 if (packageName != null) {
5439 PackageInfo app = null;
5440 try {
5441 app = mPackageManager.getPackageInfo(packageName, 0);
5442 } catch (NameNotFoundException nnf) {
5443 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5444 throw new IllegalArgumentException("Package " + packageName + " not found");
5445 }
5446
5447 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5448 // So: using the current active transport, and the caller has asked
5449 // that its own package will be restored. In this narrow use case
5450 // we do not require the caller to hold the permission.
5451 needPermission = false;
5452 }
5453 }
5454 }
5455
5456 if (needPermission) {
5457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5458 "beginRestoreSession");
5459 } else {
5460 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5461 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005462
5463 synchronized(this) {
5464 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005465 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005466 return null;
5467 }
Chris Tate44ab8452010-11-16 15:10:49 -08005468 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005469 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005470 }
5471 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005472 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005473
Christopher Tate73a3cb32010-12-13 18:27:26 -08005474 void clearRestoreSession(ActiveRestoreSession currentSession) {
5475 synchronized(this) {
5476 if (currentSession != mActiveRestoreSession) {
5477 Slog.e(TAG, "ending non-current restore session");
5478 } else {
5479 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5480 mActiveRestoreSession = null;
5481 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5482 }
5483 }
5484 }
5485
Christopher Tate44a27902010-01-27 17:15:49 -08005486 // Note that a currently-active backup agent has notified us that it has
5487 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005488 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005489 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005490 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5491 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005492 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005493 op = mCurrentOperations.get(token);
5494 if (op != null) {
5495 op.state = OP_ACKNOWLEDGED;
5496 }
Christopher Tate44a27902010-01-27 17:15:49 -08005497 mCurrentOpLock.notifyAll();
5498 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005499
5500 // The completion callback, if any, is invoked on the handler
5501 if (op != null && op.callback != null) {
5502 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5503 mBackupHandler.sendMessage(msg);
5504 }
Christopher Tate44a27902010-01-27 17:15:49 -08005505 }
5506
Christopher Tate9b3905c2009-06-08 15:24:01 -07005507 // ----- Restore session -----
5508
Christopher Tate80202c82010-01-25 19:37:47 -08005509 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005510 private static final String TAG = "RestoreSession";
5511
Chris Tate44ab8452010-11-16 15:10:49 -08005512 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005513 private IBackupTransport mRestoreTransport = null;
5514 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005515 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005516
Chris Tate44ab8452010-11-16 15:10:49 -08005517 ActiveRestoreSession(String packageName, String transport) {
5518 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005519 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005520 }
5521
5522 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005523 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005525 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005526 if (observer == null) {
5527 throw new IllegalArgumentException("Observer must not be null");
5528 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005529
Christopher Tate73a3cb32010-12-13 18:27:26 -08005530 if (mEnded) {
5531 throw new IllegalStateException("Restore session already ended");
5532 }
5533
Christopher Tate1bb69062010-02-19 17:02:12 -08005534 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005535 try {
Christopher Tate43383042009-07-13 15:17:13 -07005536 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005537 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005538 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005539 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005540 // spin off the transport request to our service thread
5541 mWakelock.acquire();
5542 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5543 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5544 mBackupHandler.sendMessage(msg);
5545 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005546 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005547 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005548 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005549 } finally {
5550 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005551 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005552 }
5553
Christopher Tate84725812010-02-04 15:52:40 -08005554 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005555 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5556 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005557
Chris Tate44ab8452010-11-16 15:10:49 -08005558 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005559 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005560
Christopher Tate73a3cb32010-12-13 18:27:26 -08005561 if (mEnded) {
5562 throw new IllegalStateException("Restore session already ended");
5563 }
5564
Dan Egnor0084da52009-07-29 12:57:16 -07005565 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005566 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5567 return -1;
5568 }
5569
5570 if (mPackageName != null) {
5571 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005572 return -1;
5573 }
5574
Christopher Tate21ab6a52009-09-24 18:01:46 -07005575 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005576 for (int i = 0; i < mRestoreSets.length; i++) {
5577 if (token == mRestoreSets[i].token) {
5578 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005579 mWakelock.acquire();
5580 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005581 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005582 mBackupHandler.sendMessage(msg);
5583 Binder.restoreCallingIdentity(oldId);
5584 return 0;
5585 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005586 }
5587 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005588
Joe Onorato8a9b2202010-02-26 18:56:32 -08005589 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005590 return -1;
5591 }
5592
Christopher Tate284f1bb2011-07-07 14:31:18 -07005593 public synchronized int restoreSome(long token, IRestoreObserver observer,
5594 String[] packages) {
5595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5596 "performRestore");
5597
5598 if (DEBUG) {
5599 StringBuilder b = new StringBuilder(128);
5600 b.append("restoreSome token=");
5601 b.append(Long.toHexString(token));
5602 b.append(" observer=");
5603 b.append(observer.toString());
5604 b.append(" packages=");
5605 if (packages == null) {
5606 b.append("null");
5607 } else {
5608 b.append('{');
5609 boolean first = true;
5610 for (String s : packages) {
5611 if (!first) {
5612 b.append(", ");
5613 } else first = false;
5614 b.append(s);
5615 }
5616 b.append('}');
5617 }
5618 Slog.d(TAG, b.toString());
5619 }
5620
5621 if (mEnded) {
5622 throw new IllegalStateException("Restore session already ended");
5623 }
5624
5625 if (mRestoreTransport == null || mRestoreSets == null) {
5626 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5627 return -1;
5628 }
5629
5630 if (mPackageName != null) {
5631 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5632 return -1;
5633 }
5634
5635 synchronized (mQueueLock) {
5636 for (int i = 0; i < mRestoreSets.length; i++) {
5637 if (token == mRestoreSets[i].token) {
5638 long oldId = Binder.clearCallingIdentity();
5639 mWakelock.acquire();
5640 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5641 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5642 packages, true);
5643 mBackupHandler.sendMessage(msg);
5644 Binder.restoreCallingIdentity(oldId);
5645 return 0;
5646 }
5647 }
5648 }
5649
5650 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5651 return -1;
5652 }
5653
Christopher Tate84725812010-02-04 15:52:40 -08005654 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005655 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005656
Christopher Tate73a3cb32010-12-13 18:27:26 -08005657 if (mEnded) {
5658 throw new IllegalStateException("Restore session already ended");
5659 }
5660
Chris Tate44ab8452010-11-16 15:10:49 -08005661 if (mPackageName != null) {
5662 if (! mPackageName.equals(packageName)) {
5663 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5664 + " on session for package " + mPackageName);
5665 return -1;
5666 }
5667 }
5668
Christopher Tate84725812010-02-04 15:52:40 -08005669 PackageInfo app = null;
5670 try {
5671 app = mPackageManager.getPackageInfo(packageName, 0);
5672 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005673 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005674 return -1;
5675 }
5676
5677 // If the caller is not privileged and is not coming from the target
5678 // app's uid, throw a permission exception back to the caller.
5679 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5680 Binder.getCallingPid(), Binder.getCallingUid());
5681 if ((perm == PackageManager.PERMISSION_DENIED) &&
5682 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005683 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005684 + " or calling uid=" + Binder.getCallingUid());
5685 throw new SecurityException("No permission to restore other packages");
5686 }
5687
Christopher Tate7d411a32010-02-26 11:27:08 -08005688 // If the package has no backup agent, we obviously cannot proceed
5689 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005690 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005691 return -1;
5692 }
5693
Christopher Tate84725812010-02-04 15:52:40 -08005694 // So far so good; we're allowed to try to restore this package. Now
5695 // check whether there is data for it in the current dataset, falling back
5696 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005697 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005698
5699 // If we didn't come up with a place to look -- no ancestral dataset and
5700 // the app has never been backed up from this device -- there's nothing
5701 // to do but return failure.
5702 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005703 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005704 return -1;
5705 }
5706
5707 // Ready to go: enqueue the restore request and claim success
5708 long oldId = Binder.clearCallingIdentity();
5709 mWakelock.acquire();
5710 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005711 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005712 mBackupHandler.sendMessage(msg);
5713 Binder.restoreCallingIdentity(oldId);
5714 return 0;
5715 }
5716
Christopher Tate73a3cb32010-12-13 18:27:26 -08005717 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5718 class EndRestoreRunnable implements Runnable {
5719 BackupManagerService mBackupManager;
5720 ActiveRestoreSession mSession;
5721
5722 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5723 mBackupManager = manager;
5724 mSession = session;
5725 }
5726
5727 public void run() {
5728 // clean up the session's bookkeeping
5729 synchronized (mSession) {
5730 try {
5731 if (mSession.mRestoreTransport != null) {
5732 mSession.mRestoreTransport.finishRestore();
5733 }
5734 } catch (Exception e) {
5735 Slog.e(TAG, "Error in finishRestore", e);
5736 } finally {
5737 mSession.mRestoreTransport = null;
5738 mSession.mEnded = true;
5739 }
5740 }
5741
5742 // clean up the BackupManagerService side of the bookkeeping
5743 // and cancel any pending timeout message
5744 mBackupManager.clearRestoreSession(mSession);
5745 }
5746 }
5747
Dan Egnor0084da52009-07-29 12:57:16 -07005748 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005749 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005750
Christopher Tate73a3cb32010-12-13 18:27:26 -08005751 if (mEnded) {
5752 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005753 }
5754
Christopher Tate73a3cb32010-12-13 18:27:26 -08005755 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005756 }
5757 }
5758
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005759 @Override
5760 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5762
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005763 long identityToken = Binder.clearCallingIdentity();
5764 try {
5765 dumpInternal(pw);
5766 } finally {
5767 Binder.restoreCallingIdentity(identityToken);
5768 }
5769 }
5770
5771 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005772 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005773 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005774 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005775 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005776 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005777 if (mBackupRunning) pw.println("Backup currently running");
5778 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005779 + " (now = " + System.currentTimeMillis() + ')');
5780 pw.println(" next scheduled: " + mNextBackupPass);
5781
Christopher Tate91717492009-06-26 21:07:13 -07005782 pw.println("Available transports:");
5783 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005784 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5785 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005786 IBackupTransport transport = getTransport(t);
5787 File dir = new File(mBaseStateDir, transport.transportDirName());
5788 pw.println(" destination: " + transport.currentDestinationString());
5789 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005790 for (File f : dir.listFiles()) {
5791 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5792 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005793 } catch (Exception e) {
5794 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005795 pw.println(" Error: " + e);
5796 }
Christopher Tate91717492009-06-26 21:07:13 -07005797 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005798
5799 pw.println("Pending init: " + mPendingInits.size());
5800 for (String s : mPendingInits) {
5801 pw.println(" " + s);
5802 }
5803
Christopher Tate6de74ff2012-01-17 15:20:32 -08005804 if (DEBUG_BACKUP_TRACE) {
5805 synchronized (mBackupTrace) {
5806 if (!mBackupTrace.isEmpty()) {
5807 pw.println("Most recent backup trace:");
5808 for (String s : mBackupTrace) {
5809 pw.println(" " + s);
5810 }
5811 }
5812 }
5813 }
5814
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005815 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005816 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005817 for (int i=0; i<N; i++) {
5818 int uid = mBackupParticipants.keyAt(i);
5819 pw.print(" uid: ");
5820 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005821 HashSet<String> participants = mBackupParticipants.valueAt(i);
5822 for (String app: participants) {
5823 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005824 }
5825 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005826
Christopher Tateb49ceb32010-02-08 16:22:24 -08005827 pw.println("Ancestral packages: "
5828 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005829 if (mAncestralPackages != null) {
5830 for (String pkg : mAncestralPackages) {
5831 pw.println(" " + pkg);
5832 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005833 }
5834
Christopher Tate73e02522009-07-15 14:18:26 -07005835 pw.println("Ever backed up: " + mEverStoredApps.size());
5836 for (String pkg : mEverStoredApps) {
5837 pw.println(" " + pkg);
5838 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005839
5840 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005841 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005842 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005843 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005844 }
5845 }
Christopher Tate487529a2009-04-29 14:03:25 -07005846}