blob: 91e3330adebf687c5f152b6f30d7978535f963aa [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate79ec80d2011-06-24 14:58:49 -070026import android.app.backup.BackupAgent;
Christopher Tate4a627c72011-04-01 14:43:32 -070027import android.app.backup.BackupDataOutput;
28import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060029import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070031import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070034import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.ComponentName;
Christopher Tated2c0cd42011-09-15 15:51:29 -070037import android.content.ContentResolver;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.content.Context;
39import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070041import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070042import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070043import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070044import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070045import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080046import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070047import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070048import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060049import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060050import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate97ea1222012-05-17 14:59:41 -070051import android.database.ContentObserver;
Christopher Tate3799bc22009-05-06 16:13:56 -070052import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070054import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070055import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080060import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070061import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070062import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070063import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070064import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.os.RemoteException;
rpcraigebab0ae2012-12-04 09:37:23 -050066import android.os.SELinux;
Christopher Tate32418be2011-10-10 13:51:12 -070067import android.os.ServiceManager;
Dan Egnorbb9001c2009-07-27 12:20:13 -070068import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070070import android.os.WorkSource;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070071import android.os.Environment.UserEnvironment;
Christopher Tate32418be2011-10-10 13:51:12 -070072import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080073import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070074import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070075import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080076import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070077import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070078import android.util.StringBuilderPrinter;
79
Jason parksa3cdaa52011-01-13 14:15:43 -060080import com.android.internal.backup.BackupConstants;
81import com.android.internal.backup.IBackupTransport;
82import com.android.internal.backup.LocalTransport;
83import com.android.server.PackageManagerBackupAgent.Metadata;
84
Christopher Tate2efd2db2011-07-19 16:32:49 -070085import java.io.BufferedInputStream;
86import java.io.BufferedOutputStream;
87import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070088import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070089import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070090import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070091import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070092import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070093import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080094import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070095import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070096import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070097import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070098import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070099import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -0700100import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700101import java.security.InvalidAlgorithmParameterException;
102import java.security.InvalidKeyException;
103import java.security.Key;
104import java.security.NoSuchAlgorithmException;
105import java.security.SecureRandom;
106import java.security.spec.InvalidKeySpecException;
107import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700108import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400109import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700110import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700111import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400112import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700113import java.util.HashSet;
114import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700115import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700116import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800117import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700118import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700119import java.util.zip.Deflater;
120import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700121import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700122
Christopher Tate2efd2db2011-07-19 16:32:49 -0700123import javax.crypto.BadPaddingException;
124import javax.crypto.Cipher;
125import javax.crypto.CipherInputStream;
126import javax.crypto.CipherOutputStream;
127import javax.crypto.IllegalBlockSizeException;
128import javax.crypto.NoSuchPaddingException;
129import javax.crypto.SecretKey;
130import javax.crypto.SecretKeyFactory;
131import javax.crypto.spec.IvParameterSpec;
132import javax.crypto.spec.PBEKeySpec;
133import javax.crypto.spec.SecretKeySpec;
134
Christopher Tate487529a2009-04-29 14:03:25 -0700135class BackupManagerService extends IBackupManager.Stub {
136 private static final String TAG = "BackupManagerService";
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800137 private static final boolean DEBUG = false;
Christopher Tateb1543a92011-09-07 12:11:09 -0700138 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700139
140 // Name and current contents version of the full-backup manifest file
141 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
142 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700143 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
144 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700145 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700146
Christopher Tate73d73692012-01-20 17:11:31 -0800147 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
148
Christopher Tate49401dd2009-07-01 12:34:29 -0700149 // How often we perform a backup pass. Privileged external callers can
150 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700151 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700152
Dan Egnorc1c49c02009-10-30 17:35:39 -0700153 // Random variation in backup scheduling time to avoid server load spikes
154 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
155
Christopher Tate8031a3d2009-07-06 16:36:05 -0700156 // The amount of time between the initial provisioning of the device and
157 // the first backup pass.
158 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
159
Christopher Tate45281862010-03-05 15:46:30 -0800160 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
161 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
162 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700163 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700164 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700165 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700166 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700167 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700168 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
169 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800170 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700171 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
172 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700173
Christopher Tate8e294d42011-08-31 20:37:12 -0700174 // backup task state machine tick
175 static final int MSG_BACKUP_RESTORE_STEP = 20;
176 static final int MSG_OP_COMPLETE = 21;
177
Christopher Tatec7b31e32009-06-10 15:49:30 -0700178 // Timeout interval for deciding that a bind or clear-data has taken too long
179 static final long TIMEOUT_INTERVAL = 10 * 1000;
180
Christopher Tate44a27902010-01-27 17:15:49 -0800181 // Timeout intervals for agent backup & restore operations
182 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700183 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700184 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800185 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
186
Christopher Tate2efd2db2011-07-19 16:32:49 -0700187 // User confirmation timeout for a full backup/restore operation. It's this long in
188 // order to give them time to enter the backup password.
189 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700190
Christopher Tate487529a2009-04-29 14:03:25 -0700191 private Context mContext;
192 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800193 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700194 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700195 private PowerManager mPowerManager;
196 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700197 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800198 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700199
Christopher Tate73e02522009-07-15 14:18:26 -0700200 boolean mEnabled; // access to this is synchronized on 'this'
201 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800202 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700203 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800204 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800205 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700206 PendingIntent mRunBackupIntent, mRunInitIntent;
207 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tatea3d55342012-03-27 13:16:18 -0700208 // map UIDs to the set of participating packages under that UID
209 final SparseArray<HashSet<String>> mBackupParticipants
210 = new SparseArray<HashSet<String>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700211 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700212 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700213 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700214
Christopher Tatecc55f812011-08-16 16:06:53 -0700215 BackupRequest(String pkgName) {
216 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700217 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700218
219 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700220 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700221 }
Christopher Tate46758122009-05-06 11:22:00 -0700222 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800223 // Backups that we haven't started yet. Keys are package names.
224 HashMap<String,BackupRequest> mPendingBackups
225 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700226
227 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700228 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700229
230 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700231 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700232
Christopher Tate043dadc2009-06-02 16:11:00 -0700233 // The thread performing the sequence of queued backups binds to each app's agent
234 // in succession. Bind notifications are asynchronously delivered through the
235 // Activity Manager; use this lock object to signal when a requested binding has
236 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700237 final Object mAgentConnectLock = new Object();
238 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700239 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700240 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700241 volatile long mLastBackupPass;
242 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700243
Christopher Tate6de74ff2012-01-17 15:20:32 -0800244 // For debugging, we maintain a progress trace of operations during backup
245 static final boolean DEBUG_BACKUP_TRACE = true;
246 final List<String> mBackupTrace = new ArrayList<String>();
247
Christopher Tate55f931a2009-09-29 17:17:34 -0700248 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700249 final Object mClearDataLock = new Object();
250 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700251
Christopher Tate91717492009-06-26 21:07:13 -0700252 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700253 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700254 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700255 String mCurrentTransport;
256 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800257 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700258
Christopher Tate97ea1222012-05-17 14:59:41 -0700259 // Watch the device provisioning operation during setup
260 ContentObserver mProvisionedObserver;
261
262 class ProvisionedObserver extends ContentObserver {
263 public ProvisionedObserver(Handler handler) {
264 super(handler);
265 }
266
267 public void onChange(boolean selfChange) {
268 final boolean wasProvisioned = mProvisioned;
269 final boolean isProvisioned = deviceIsProvisioned();
270 // latch: never unprovision
271 mProvisioned = wasProvisioned || isProvisioned;
272 if (MORE_DEBUG) {
273 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
274 + " is=" + isProvisioned + " now=" + mProvisioned);
275 }
276
277 synchronized (mQueueLock) {
278 if (mProvisioned && !wasProvisioned && mEnabled) {
279 // we're now good to go, so start the backup alarms
280 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
281 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
282 }
283 }
284 }
285 }
286
Christopher Tate2d449afe2010-03-29 19:14:24 -0700287 class RestoreGetSetsParams {
288 public IBackupTransport transport;
289 public ActiveRestoreSession session;
290 public IRestoreObserver observer;
291
292 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
293 IRestoreObserver _observer) {
294 transport = _transport;
295 session = _session;
296 observer = _observer;
297 }
298 }
299
Christopher Tate73e02522009-07-15 14:18:26 -0700300 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700301 public IBackupTransport transport;
302 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700303 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800304 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800305 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700306 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700307 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800308
309 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700310 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800311 transport = _transport;
312 observer = _obs;
313 token = _token;
314 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800315 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700316 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700317 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800318 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700319
Chris Tate249345b2010-10-29 12:57:04 -0700320 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
321 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700322 transport = _transport;
323 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700324 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800325 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800326 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700327 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700328 filterSet = null;
329 }
330
331 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
332 String[] _filterSet, boolean _needFullBackup) {
333 transport = _transport;
334 observer = _obs;
335 token = _token;
336 pkgInfo = null;
337 pmToken = 0;
338 needFullBackup = _needFullBackup;
339 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700340 }
341 }
342
Christopher Tate73e02522009-07-15 14:18:26 -0700343 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700344 public IBackupTransport transport;
345 public PackageInfo packageInfo;
346
347 ClearParams(IBackupTransport _transport, PackageInfo _info) {
348 transport = _transport;
349 packageInfo = _info;
350 }
351 }
352
Christopher Tate4a627c72011-04-01 14:43:32 -0700353 class FullParams {
354 public ParcelFileDescriptor fd;
355 public final AtomicBoolean latch;
356 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700357 public String curPassword; // filled in by the confirmation step
358 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700359
360 FullParams() {
361 latch = new AtomicBoolean(false);
362 }
363 }
364
365 class FullBackupParams extends FullParams {
366 public boolean includeApks;
367 public boolean includeShared;
368 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700369 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700370 public String[] packages;
371
372 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700373 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700374 fd = output;
375 includeApks = saveApks;
376 includeShared = saveShared;
377 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700378 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700379 packages = pkgList;
380 }
381 }
382
383 class FullRestoreParams extends FullParams {
384 FullRestoreParams(ParcelFileDescriptor input) {
385 fd = input;
386 }
387 }
388
Christopher Tate44a27902010-01-27 17:15:49 -0800389 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
390 // token is the index of the entry in the pending-operations list.
391 static final int OP_PENDING = 0;
392 static final int OP_ACKNOWLEDGED = 1;
393 static final int OP_TIMEOUT = -1;
394
Christopher Tate8e294d42011-08-31 20:37:12 -0700395 class Operation {
396 public int state;
397 public BackupRestoreTask callback;
398
399 Operation(int initialState, BackupRestoreTask callbackObj) {
400 state = initialState;
401 callback = callbackObj;
402 }
403 }
404 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800405 final Object mCurrentOpLock = new Object();
406 final Random mTokenGenerator = new Random();
407
Christopher Tate4a627c72011-04-01 14:43:32 -0700408 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
409
Christopher Tate5cb400b2009-06-25 16:03:14 -0700410 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700411 File mBaseStateDir;
412 File mDataDir;
413 File mJournalDir;
414 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700415
Christopher Tate2efd2db2011-07-19 16:32:49 -0700416 // Backup password, if any, and the file where it's saved. What is stored is not the
417 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
418 // persisted) salt. Validation is performed by running the challenge text through the
419 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
420 // the saved hash string, then the challenge text matches the originally supplied
421 // password text.
422 private final SecureRandom mRng = new SecureRandom();
423 private String mPasswordHash;
424 private File mPasswordHashFile;
425 private byte[] mPasswordSalt;
426
427 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
428 static final int PBKDF2_HASH_ROUNDS = 10000;
429 static final int PBKDF2_KEY_SIZE = 256; // bits
430 static final int PBKDF2_SALT_SIZE = 512; // bits
431 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
432
Christopher Tate84725812010-02-04 15:52:40 -0800433 // Keep a log of all the apps we've ever backed up, and what the
434 // dataset tokens are for both the current backup dataset and
435 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700436 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700437 HashSet<String> mEverStoredApps = new HashSet<String>();
438
Christopher Tateb49ceb32010-02-08 16:22:24 -0800439 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800440 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800441 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800442 long mAncestralToken = 0;
443 long mCurrentToken = 0;
444
Christopher Tate4cc86e12009-09-21 19:36:51 -0700445 // Persistently track the need to do a full init
446 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
447 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700448
Christopher Tate4a627c72011-04-01 14:43:32 -0700449 // Utility: build a new random integer token
450 int generateToken() {
451 int token;
452 do {
453 synchronized (mTokenGenerator) {
454 token = mTokenGenerator.nextInt();
455 }
456 } while (token < 0);
457 return token;
458 }
459
Christopher Tate44a27902010-01-27 17:15:49 -0800460 // ----- Asynchronous backup/restore handler thread -----
461
462 private class BackupHandler extends Handler {
463 public BackupHandler(Looper looper) {
464 super(looper);
465 }
466
467 public void handleMessage(Message msg) {
468
469 switch (msg.what) {
470 case MSG_RUN_BACKUP:
471 {
472 mLastBackupPass = System.currentTimeMillis();
473 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
474
475 IBackupTransport transport = getTransport(mCurrentTransport);
476 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800477 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700478 synchronized (mQueueLock) {
479 mBackupRunning = false;
480 }
Christopher Tate44a27902010-01-27 17:15:49 -0800481 mWakelock.release();
482 break;
483 }
484
485 // snapshot the pending-backup set and work on that
486 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800487 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800488 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800489 // Do we have any work to do? Construct the work queue
490 // then release the synchronization lock to actually run
491 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800492 if (mPendingBackups.size() > 0) {
493 for (BackupRequest b: mPendingBackups.values()) {
494 queue.add(b);
495 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800496 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800497 mPendingBackups.clear();
498
499 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800500 mJournal = null;
501
Christopher Tate44a27902010-01-27 17:15:49 -0800502 }
503 }
Christopher Tatec61da312010-02-05 10:41:27 -0800504
Christopher Tate8e294d42011-08-31 20:37:12 -0700505 // At this point, we have started a new journal file, and the old
506 // file identity is being passed to the backup processing task.
507 // When it completes successfully, that old journal file will be
508 // deleted. If we crash prior to that, the old journal is parsed
509 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800510 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700511 // Spin up a backup state sequence and set it running
512 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
513 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
514 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800515 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800516 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700517 synchronized (mQueueLock) {
518 mBackupRunning = false;
519 }
Christopher Tatec61da312010-02-05 10:41:27 -0800520 mWakelock.release();
521 }
Christopher Tate44a27902010-01-27 17:15:49 -0800522 break;
523 }
524
Christopher Tate8e294d42011-08-31 20:37:12 -0700525 case MSG_BACKUP_RESTORE_STEP:
526 {
527 try {
528 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
529 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
530 task.execute();
531 } catch (ClassCastException e) {
532 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
533 }
534 break;
535 }
536
537 case MSG_OP_COMPLETE:
538 {
539 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700540 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
541 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700542 } catch (ClassCastException e) {
543 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
544 }
545 break;
546 }
547
Christopher Tate44a27902010-01-27 17:15:49 -0800548 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700549 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700550 // TODO: refactor full backup to be a looper-based state machine
551 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700552 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700553 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
554 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700555 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700556 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700557 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800558 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700559 }
Christopher Tate44a27902010-01-27 17:15:49 -0800560
561 case MSG_RUN_RESTORE:
562 {
563 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800564 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700565 PerformRestoreTask task = new PerformRestoreTask(
566 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700567 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700568 params.needFullBackup, params.filterSet);
569 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
570 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800571 break;
572 }
573
Christopher Tate75a99702011-05-18 16:28:19 -0700574 case MSG_RUN_FULL_RESTORE:
575 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700576 // TODO: refactor full restore to be a looper-based state machine
577 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700578 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700579 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
580 params.curPassword, params.encryptPassword,
581 params.observer, params.latch);
582 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700583 break;
584 }
585
Christopher Tate44a27902010-01-27 17:15:49 -0800586 case MSG_RUN_CLEAR:
587 {
588 ClearParams params = (ClearParams)msg.obj;
589 (new PerformClearTask(params.transport, params.packageInfo)).run();
590 break;
591 }
592
593 case MSG_RUN_INITIALIZE:
594 {
595 HashSet<String> queue;
596
597 // Snapshot the pending-init queue and work on that
598 synchronized (mQueueLock) {
599 queue = new HashSet<String>(mPendingInits);
600 mPendingInits.clear();
601 }
602
603 (new PerformInitializeTask(queue)).run();
604 break;
605 }
606
Christopher Tate2d449afe2010-03-29 19:14:24 -0700607 case MSG_RUN_GET_RESTORE_SETS:
608 {
609 // Like other async operations, this is entered with the wakelock held
610 RestoreSet[] sets = null;
611 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
612 try {
613 sets = params.transport.getAvailableRestoreSets();
614 // cache the result in the active session
615 synchronized (params.session) {
616 params.session.mRestoreSets = sets;
617 }
618 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
619 } catch (Exception e) {
620 Slog.e(TAG, "Error from transport getting set list");
621 } finally {
622 if (params.observer != null) {
623 try {
624 params.observer.restoreSetsAvailable(sets);
625 } catch (RemoteException re) {
626 Slog.e(TAG, "Unable to report listing to observer");
627 } catch (Exception e) {
628 Slog.e(TAG, "Restore observer threw", e);
629 }
630 }
631
Christopher Tate2a935092011-03-03 17:30:32 -0800632 // Done: reset the session timeout clock
633 removeMessages(MSG_RESTORE_TIMEOUT);
634 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
635
Christopher Tate2d449afe2010-03-29 19:14:24 -0700636 mWakelock.release();
637 }
638 break;
639 }
640
Christopher Tate44a27902010-01-27 17:15:49 -0800641 case MSG_TIMEOUT:
642 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700643 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800644 break;
645 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800646
647 case MSG_RESTORE_TIMEOUT:
648 {
649 synchronized (BackupManagerService.this) {
650 if (mActiveRestoreSession != null) {
651 // Client app left the restore session dangling. We know that it
652 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700653 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800654 // up now.
655 Slog.w(TAG, "Restore session timed out; aborting");
656 post(mActiveRestoreSession.new EndRestoreRunnable(
657 BackupManagerService.this, mActiveRestoreSession));
658 }
659 }
660 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700661
662 case MSG_FULL_CONFIRMATION_TIMEOUT:
663 {
664 synchronized (mFullConfirmations) {
665 FullParams params = mFullConfirmations.get(msg.arg1);
666 if (params != null) {
667 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
668
669 // Release the waiter; timeout == completion
670 signalFullBackupRestoreCompletion(params);
671
672 // Remove the token from the set
673 mFullConfirmations.delete(msg.arg1);
674
675 // Report a timeout to the observer, if any
676 if (params.observer != null) {
677 try {
678 params.observer.onTimeout();
679 } catch (RemoteException e) {
680 /* don't care if the app has gone away */
681 }
682 }
683 } else {
684 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
685 }
686 }
687 break;
688 }
Christopher Tate44a27902010-01-27 17:15:49 -0800689 }
690 }
691 }
692
Christopher Tate6de74ff2012-01-17 15:20:32 -0800693 // ----- Debug-only backup operation trace -----
694 void addBackupTrace(String s) {
695 if (DEBUG_BACKUP_TRACE) {
696 synchronized (mBackupTrace) {
697 mBackupTrace.add(s);
698 }
699 }
700 }
701
702 void clearBackupTrace() {
703 if (DEBUG_BACKUP_TRACE) {
704 synchronized (mBackupTrace) {
705 mBackupTrace.clear();
706 }
707 }
708 }
709
Christopher Tate44a27902010-01-27 17:15:49 -0800710 // ----- Main service implementation -----
711
Christopher Tate487529a2009-04-29 14:03:25 -0700712 public BackupManagerService(Context context) {
713 mContext = context;
714 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700715 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700716 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700717
Christopher Tateb6787f22009-07-02 17:40:45 -0700718 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
719 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700720 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700721
Christopher Tate44a27902010-01-27 17:15:49 -0800722 mBackupManagerBinder = asInterface(asBinder());
723
724 // spin up the backup/restore handler thread
725 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
726 mHandlerThread.start();
727 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
728
Christopher Tate22b87872009-05-04 16:41:53 -0700729 // Set up our bookkeeping
Christopher Tate97ea1222012-05-17 14:59:41 -0700730 final ContentResolver resolver = context.getContentResolver();
731 boolean areEnabled = Settings.Secure.getInt(resolver,
Dianne Hackborncf098292009-07-01 19:55:20 -0700732 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700733 mProvisioned = Settings.Global.getInt(resolver,
734 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700735 mAutoRestore = Settings.Secure.getInt(resolver,
Christopher Tate5035fda2010-02-25 18:01:14 -0800736 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Christopher Tate97ea1222012-05-17 14:59:41 -0700737
738 mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
739 resolver.registerContentObserver(
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700740 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
Christopher Tate97ea1222012-05-17 14:59:41 -0700741 false, mProvisionedObserver);
742
Oscar Montemayora8529f62009-11-18 10:14:20 -0800743 // If Encrypted file systems is enabled or disabled, this call will return the
744 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600745 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800746 mBaseStateDir.mkdirs();
rpcraigebab0ae2012-12-04 09:37:23 -0500747 if (!SELinux.restorecon(mBaseStateDir)) {
748 Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
749 }
Christopher Tatef4172472009-05-05 15:50:03 -0700750 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700751
Christopher Tate2efd2db2011-07-19 16:32:49 -0700752 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
753 if (mPasswordHashFile.exists()) {
754 FileInputStream fin = null;
755 DataInputStream in = null;
756 try {
757 fin = new FileInputStream(mPasswordHashFile);
758 in = new DataInputStream(new BufferedInputStream(fin));
759 // integer length of the salt array, followed by the salt,
760 // then the hex pw hash string
761 int saltLen = in.readInt();
762 byte[] salt = new byte[saltLen];
763 in.readFully(salt);
764 mPasswordHash = in.readUTF();
765 mPasswordSalt = salt;
766 } catch (IOException e) {
767 Slog.e(TAG, "Unable to read saved backup pw hash");
768 } finally {
769 try {
770 if (in != null) in.close();
771 if (fin != null) fin.close();
772 } catch (IOException e) {
773 Slog.w(TAG, "Unable to close streams");
774 }
775 }
776 }
777
Christopher Tate4cc86e12009-09-21 19:36:51 -0700778 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700779 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700780 IntentFilter filter = new IntentFilter();
781 filter.addAction(RUN_BACKUP_ACTION);
782 context.registerReceiver(mRunBackupReceiver, filter,
783 android.Manifest.permission.BACKUP, null);
784
785 mRunInitReceiver = new RunInitializeReceiver();
786 filter = new IntentFilter();
787 filter.addAction(RUN_INITIALIZE_ACTION);
788 context.registerReceiver(mRunInitReceiver, filter,
789 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700790
791 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700792 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
793 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
794
Christopher Tate4cc86e12009-09-21 19:36:51 -0700795 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
796 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
797 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
798
Christopher Tatecde87f42009-06-12 12:55:53 -0700799 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700800 mJournalDir = new File(mBaseStateDir, "pending");
801 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700802 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700803
Christopher Tate73e02522009-07-15 14:18:26 -0700804 // Set up the various sorts of package tracking we do
805 initPackageTracking();
806
Christopher Tateabce4e82009-06-18 18:35:32 -0700807 // Build our mapping of uid to backup client services. This implicitly
808 // schedules a backup pass on the Package Manager metadata the first
809 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700810 synchronized (mBackupParticipants) {
811 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700812 }
813
Dan Egnor87a02bc2009-06-17 02:30:10 -0700814 // Set up our transport options and initialize the default transport
815 // TODO: Have transports register themselves somehow?
816 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700817 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700818 ComponentName localName = new ComponentName(context, LocalTransport.class);
819 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700820
Christopher Tate91717492009-06-26 21:07:13 -0700821 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700822 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
823 Settings.Secure.BACKUP_TRANSPORT);
824 if ("".equals(mCurrentTransport)) {
825 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700826 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700828
829 // Attach to the Google backup transport. When this comes up, it will set
830 // itself as the current transport because we explicitly reset mCurrentTransport
831 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700832 ComponentName transportComponent = new ComponentName("com.google.android.backup",
833 "com.google.android.backup.BackupTransportService");
834 try {
835 // If there's something out there that is supposed to be the Google
836 // backup transport, make sure it's legitimately part of the OS build
837 // and not an app lying about its package name.
838 ApplicationInfo info = mPackageManager.getApplicationInfo(
839 transportComponent.getPackageName(), 0);
840 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
841 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
842 Intent intent = new Intent().setComponent(transportComponent);
Amith Yamasanicd757062012-10-19 18:23:52 -0700843 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE,
844 UserHandle.USER_OWNER);
Christopher Tatea32504f2010-04-21 17:58:07 -0700845 } else {
846 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
847 }
848 } catch (PackageManager.NameNotFoundException nnf) {
849 // No such package? No binding.
850 if (DEBUG) Slog.v(TAG, "Google transport not present");
851 }
Christopher Tateaa088442009-06-16 18:25:46 -0700852
Christopher Tatecde87f42009-06-12 12:55:53 -0700853 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700854 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700855 parseLeftoverJournals();
856
Christopher Tateb6787f22009-07-02 17:40:45 -0700857 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700858 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700859
860 // Start the backup passes going
861 setBackupEnabled(areEnabled);
862 }
863
864 private class RunBackupReceiver extends BroadcastReceiver {
865 public void onReceive(Context context, Intent intent) {
866 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700867 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700868 if (mPendingInits.size() > 0) {
869 // If there are pending init operations, we process those
870 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700872 try {
873 mAlarmManager.cancel(mRunInitIntent);
874 mRunInitIntent.send();
875 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700877 // can't really do more than bail here
878 }
879 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800880 // Don't run backups now if we're disabled or not yet
881 // fully set up.
882 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700883 if (!mBackupRunning) {
884 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700885
Christopher Tate336a6492011-10-05 16:05:43 -0700886 // Acquire the wakelock and pass it to the backup thread. it will
887 // be released once backup concludes.
888 mBackupRunning = true;
889 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700890
Christopher Tate336a6492011-10-05 16:05:43 -0700891 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
892 mBackupHandler.sendMessage(msg);
893 } else {
894 Slog.i(TAG, "Backup time but one already running");
895 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700896 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800897 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700898 }
899 }
900 }
901 }
902 }
903 }
904
905 private class RunInitializeReceiver extends BroadcastReceiver {
906 public void onReceive(Context context, Intent intent) {
907 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
908 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800909 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700910
911 // Acquire the wakelock and pass it to the init thread. it will
912 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700913 mWakelock.acquire();
914
Christopher Tate4cc86e12009-09-21 19:36:51 -0700915 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700916 mBackupHandler.sendMessage(msg);
917 }
918 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700919 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700920 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700921
Christopher Tate73e02522009-07-15 14:18:26 -0700922 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800923 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700924
Christopher Tate84725812010-02-04 15:52:40 -0800925 // Remember our ancestral dataset
926 mTokenFile = new File(mBaseStateDir, "ancestral");
927 try {
928 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800929 int version = tf.readInt();
930 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
931 mAncestralToken = tf.readLong();
932 mCurrentToken = tf.readLong();
933
934 int numPackages = tf.readInt();
935 if (numPackages >= 0) {
936 mAncestralPackages = new HashSet<String>();
937 for (int i = 0; i < numPackages; i++) {
938 String pkgName = tf.readUTF();
939 mAncestralPackages.add(pkgName);
940 }
941 }
942 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800943 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800944 } catch (FileNotFoundException fnf) {
945 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800946 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800947 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800948 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800949 }
950
Christopher Tatee97e8072009-07-15 16:45:50 -0700951 // Keep a log of what apps we've ever backed up. Because we might have
952 // rebooted in the middle of an operation that was removing something from
953 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700954 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700955 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700956
Christopher Tatee97e8072009-07-15 16:45:50 -0700957 // If we were in the middle of removing something from the ever-backed-up
958 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700959 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700960 if (tempProcessedFile.exists()) {
961 tempProcessedFile.delete();
962 }
963
Dan Egnor852f8e42009-09-30 11:20:45 -0700964 // If there are previous contents, parse them out then start a new
965 // file to continue the recordkeeping.
966 if (mEverStored.exists()) {
967 RandomAccessFile temp = null;
968 RandomAccessFile in = null;
969
970 try {
971 temp = new RandomAccessFile(tempProcessedFile, "rws");
972 in = new RandomAccessFile(mEverStored, "r");
973
974 while (true) {
975 PackageInfo info;
976 String pkg = in.readUTF();
977 try {
978 info = mPackageManager.getPackageInfo(pkg, 0);
979 mEverStoredApps.add(pkg);
980 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700981 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700982 } catch (NameNotFoundException e) {
983 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700984 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700985 }
986 }
987 } catch (EOFException e) {
988 // Once we've rewritten the backup history log, atomically replace the
989 // old one with the new one then reopen the file for continuing use.
990 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700992 }
993 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800994 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700995 } finally {
996 try { if (temp != null) temp.close(); } catch (IOException e) {}
997 try { if (in != null) in.close(); } catch (IOException e) {}
998 }
999 }
1000
Christopher Tate73e02522009-07-15 14:18:26 -07001001 // Register for broadcasts about package install, etc., so we can
1002 // update the provider list.
1003 IntentFilter filter = new IntentFilter();
1004 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1005 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1006 filter.addDataScheme("package");
1007 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001008 // Register for events related to sdcard installation.
1009 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001010 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1011 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001012 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -07001013 }
1014
Christopher Tatecde87f42009-06-12 12:55:53 -07001015 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -07001016 for (File f : mJournalDir.listFiles()) {
1017 if (mJournal == null || f.compareTo(mJournal) != 0) {
1018 // This isn't the current journal, so it must be a leftover. Read
1019 // out the package names mentioned there and schedule them for
1020 // backup.
1021 RandomAccessFile in = null;
1022 try {
Joe Onorato431bb222010-10-18 19:13:23 -04001023 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -07001024 in = new RandomAccessFile(f, "r");
1025 while (true) {
1026 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -04001027 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001028 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -07001029 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001030 } catch (EOFException e) {
1031 // no more data; we're done
1032 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001033 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001034 } finally {
1035 // close/delete the file
1036 try { if (in != null) in.close(); } catch (IOException e) {}
1037 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -07001038 }
1039 }
1040 }
1041 }
1042
Christopher Tate2efd2db2011-07-19 16:32:49 -07001043 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1044 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1045 }
1046
1047 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1048 try {
1049 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1050 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1051 return keyFactory.generateSecret(ks);
1052 } catch (InvalidKeySpecException e) {
1053 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1054 } catch (NoSuchAlgorithmException e) {
1055 Slog.e(TAG, "PBKDF2 unavailable!");
1056 }
1057 return null;
1058 }
1059
1060 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1061 SecretKey key = buildPasswordKey(pw, salt, rounds);
1062 if (key != null) {
1063 return byteArrayToHex(key.getEncoded());
1064 }
1065 return null;
1066 }
1067
1068 private String byteArrayToHex(byte[] data) {
1069 StringBuilder buf = new StringBuilder(data.length * 2);
1070 for (int i = 0; i < data.length; i++) {
1071 buf.append(Byte.toHexString(data[i], true));
1072 }
1073 return buf.toString();
1074 }
1075
1076 private byte[] hexToByteArray(String digits) {
1077 final int bytes = digits.length() / 2;
1078 if (2*bytes != digits.length()) {
1079 throw new IllegalArgumentException("Hex string must have an even number of digits");
1080 }
1081
1082 byte[] result = new byte[bytes];
1083 for (int i = 0; i < digits.length(); i += 2) {
1084 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1085 }
1086 return result;
1087 }
1088
1089 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1090 char[] mkAsChar = new char[pwBytes.length];
1091 for (int i = 0; i < pwBytes.length; i++) {
1092 mkAsChar[i] = (char) pwBytes[i];
1093 }
1094
1095 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1096 return checksum.getEncoded();
1097 }
1098
1099 // Used for generating random salts or passwords
1100 private byte[] randomBytes(int bits) {
1101 byte[] array = new byte[bits / 8];
1102 mRng.nextBytes(array);
1103 return array;
1104 }
1105
1106 // Backup password management
1107 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001108 // First, on an encrypted device we require matching the device pw
1109 final boolean isEncrypted;
1110 try {
1111 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1112 if (isEncrypted) {
1113 if (DEBUG) {
1114 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1115 }
1116 // 0 means the password validated
1117 // -2 means device not encrypted
1118 // Any other result is either password failure or an error condition,
1119 // so we refuse the match
1120 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1121 if (result == 0) {
1122 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1123 return true;
1124 } else if (result != -2) {
1125 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1126 return false;
1127 } else {
1128 // ...else the device is supposedly not encrypted. HOWEVER, the
1129 // query about the encryption state said that the device *is*
1130 // encrypted, so ... we may have a problem. Log it and refuse
1131 // the backup.
1132 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1133 return false;
1134 }
1135 }
1136 } catch (Exception e) {
1137 // Something went wrong talking to the mount service. This is very bad;
1138 // assume that we fail password validation.
1139 return false;
1140 }
1141
Christopher Tate2efd2db2011-07-19 16:32:49 -07001142 if (mPasswordHash == null) {
1143 // no current password case -- require that 'currentPw' be null or empty
1144 if (candidatePw == null || "".equals(candidatePw)) {
1145 return true;
1146 } // else the non-empty candidate does not match the empty stored pw
1147 } else {
1148 // hash the stated current pw and compare to the stored one
1149 if (candidatePw != null && candidatePw.length() > 0) {
1150 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1151 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1152 // candidate hash matches the stored hash -- the password matches
1153 return true;
1154 }
1155 } // else the stored pw is nonempty but the candidate is empty; no match
1156 }
1157 return false;
1158 }
1159
1160 @Override
1161 public boolean setBackupPassword(String currentPw, String newPw) {
1162 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1163 "setBackupPassword");
1164
1165 // If the supplied pw doesn't hash to the the saved one, fail
1166 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1167 return false;
1168 }
1169
1170 // Clearing the password is okay
1171 if (newPw == null || newPw.isEmpty()) {
1172 if (mPasswordHashFile.exists()) {
1173 if (!mPasswordHashFile.delete()) {
1174 // Unable to delete the old pw file, so fail
1175 Slog.e(TAG, "Unable to clear backup password");
1176 return false;
1177 }
1178 }
1179 mPasswordHash = null;
1180 mPasswordSalt = null;
1181 return true;
1182 }
1183
1184 try {
1185 // Okay, build the hash of the new backup password
1186 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1187 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1188
1189 OutputStream pwf = null, buffer = null;
1190 DataOutputStream out = null;
1191 try {
1192 pwf = new FileOutputStream(mPasswordHashFile);
1193 buffer = new BufferedOutputStream(pwf);
1194 out = new DataOutputStream(buffer);
1195 // integer length of the salt array, followed by the salt,
1196 // then the hex pw hash string
1197 out.writeInt(salt.length);
1198 out.write(salt);
1199 out.writeUTF(newPwHash);
1200 out.flush();
1201 mPasswordHash = newPwHash;
1202 mPasswordSalt = salt;
1203 return true;
1204 } finally {
1205 if (out != null) out.close();
1206 if (buffer != null) buffer.close();
1207 if (pwf != null) pwf.close();
1208 }
1209 } catch (IOException e) {
1210 Slog.e(TAG, "Unable to set backup password");
1211 }
1212 return false;
1213 }
1214
1215 @Override
1216 public boolean hasBackupPassword() {
1217 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1218 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001219
1220 try {
1221 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1222 || (mPasswordHash != null && mPasswordHash.length() > 0);
1223 } catch (Exception e) {
1224 // If we can't talk to the mount service we have a serious problem; fail
1225 // "secure" i.e. assuming that we require a password
1226 return true;
1227 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001228 }
1229
Christopher Tate4cc86e12009-09-21 19:36:51 -07001230 // Maintain persistent state around whether need to do an initialize operation.
1231 // Must be called with the queue lock held.
1232 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001233 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001234 + " on transport " + transportName);
1235 try {
1236 IBackupTransport transport = getTransport(transportName);
1237 String transportDirName = transport.transportDirName();
1238 File stateDir = new File(mBaseStateDir, transportDirName);
1239 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1240
1241 if (isPending) {
1242 // We need an init before we can proceed with sending backup data.
1243 // Record that with an entry in our set of pending inits, as well as
1244 // journaling it via creation of a sentinel file.
1245 mPendingInits.add(transportName);
1246 try {
1247 (new FileOutputStream(initPendingFile)).close();
1248 } catch (IOException ioe) {
1249 // Something is badly wrong with our permissions; just try to move on
1250 }
1251 } else {
1252 // No more initialization needed; wipe the journal and reset our state.
1253 initPendingFile.delete();
1254 mPendingInits.remove(transportName);
1255 }
1256 } catch (RemoteException e) {
1257 // can't happen; the transport is local
1258 }
1259 }
1260
Christopher Tated55e18a2009-09-21 10:12:59 -07001261 // Reset all of our bookkeeping, in response to having been told that
1262 // the backend data has been wiped [due to idle expiry, for example],
1263 // so we must re-upload all saved settings.
1264 void resetBackupState(File stateFileDir) {
1265 synchronized (mQueueLock) {
1266 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001267 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001268 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001269
Christopher Tate84725812010-02-04 15:52:40 -08001270 mCurrentToken = 0;
1271 writeRestoreTokens();
1272
Christopher Tated55e18a2009-09-21 10:12:59 -07001273 // Remove all the state files
1274 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001275 // ... but don't touch the needs-init sentinel
1276 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1277 sf.delete();
1278 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001279 }
Christopher Tate45597642011-04-04 16:59:21 -07001280 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001281
Christopher Tate45597642011-04-04 16:59:21 -07001282 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001283 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001284 final int N = mBackupParticipants.size();
Christopher Tate8e294d42011-08-31 20:37:12 -07001285 for (int i=0; i<N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001286 HashSet<String> participants = mBackupParticipants.valueAt(i);
1287 if (participants != null) {
1288 for (String packageName : participants) {
1289 dataChangedImpl(packageName);
1290 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001291 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001292 }
1293 }
1294 }
1295
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001296 // Add a transport to our set of available backends. If 'transport' is null, this
1297 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001298 private void registerTransport(String name, IBackupTransport transport) {
1299 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001301 if (transport != null) {
1302 mTransports.put(name, transport);
1303 } else {
1304 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001305 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001306 mCurrentTransport = null;
1307 }
1308 // Nothing further to do in the unregistration case
1309 return;
1310 }
Christopher Tate91717492009-06-26 21:07:13 -07001311 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001312
1313 // If the init sentinel file exists, we need to be sure to perform the init
1314 // as soon as practical. We also create the state directory at registration
1315 // time to ensure it's present from the outset.
1316 try {
1317 String transportName = transport.transportDirName();
1318 File stateDir = new File(mBaseStateDir, transportName);
1319 stateDir.mkdirs();
1320
1321 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1322 if (initSentinel.exists()) {
1323 synchronized (mQueueLock) {
1324 mPendingInits.add(transportName);
1325
1326 // TODO: pick a better starting time than now + 1 minute
1327 long delay = 1000 * 60; // one minute, in milliseconds
1328 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1329 System.currentTimeMillis() + delay, mRunInitIntent);
1330 }
1331 }
1332 } catch (RemoteException e) {
1333 // can't happen, the transport is local
1334 }
Christopher Tate91717492009-06-26 21:07:13 -07001335 }
1336
Christopher Tate3799bc22009-05-06 16:13:56 -07001337 // ----- Track installation/removal of packages -----
1338 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1339 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001340 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001341
Christopher Tate3799bc22009-05-06 16:13:56 -07001342 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001343 boolean replacing = false;
1344 boolean added = false;
1345 Bundle extras = intent.getExtras();
1346 String pkgList[] = null;
1347 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatea3d55342012-03-27 13:16:18 -07001348 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001349 Uri uri = intent.getData();
1350 if (uri == null) {
1351 return;
1352 }
1353 String pkgName = uri.getSchemeSpecificPart();
1354 if (pkgName != null) {
1355 pkgList = new String[] { pkgName };
1356 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001357 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1358 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001359 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001360 added = true;
1361 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001362 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001363 added = false;
1364 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1365 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001366
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001367 if (pkgList == null || pkgList.length == 0) {
1368 return;
1369 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001370
1371 final int uid = extras.getInt(Intent.EXTRA_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001372 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001373 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001374 if (replacing) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001375 // This is the package-replaced case; we just remove the entry
1376 // under the old uid and fall through to re-add.
1377 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001378 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001379 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001380 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001381 } else {
1382 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1384 } else {
1385 synchronized (mBackupParticipants) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001386 removePackageParticipantsLocked(pkgList, uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001387 }
1388 }
1389 }
1390 }
1391 };
1392
Dan Egnor87a02bc2009-06-17 02:30:10 -07001393 // ----- Track connection to GoogleBackupTransport service -----
1394 ServiceConnection mGoogleConnection = new ServiceConnection() {
1395 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001397 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001398 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001399 }
1400
1401 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001402 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001403 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001404 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001405 }
1406 };
1407
Christopher Tate0bacfd22012-01-11 14:41:19 -08001408 // Add the backup agents in the given packages to our set of known backup participants.
1409 // If 'packageNames' is null, adds all backup agents in the whole system.
1410 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001411 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001412 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001413 if (packageNames != null) {
1414 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1415 for (String packageName : packageNames) {
1416 addPackageParticipantsLockedInner(packageName, targetApps);
1417 }
1418 } else {
1419 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1420 addPackageParticipantsLockedInner(null, targetApps);
1421 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001422 }
1423
Christopher Tate181fafa2009-05-14 11:12:14 -07001424 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001425 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001426 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001427 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001428 }
1429
Dan Egnorefe52642009-06-24 00:16:33 -07001430 for (PackageInfo pkg : targetPkgs) {
1431 if (packageName == null || pkg.packageName.equals(packageName)) {
1432 int uid = pkg.applicationInfo.uid;
Christopher Tatea3d55342012-03-27 13:16:18 -07001433 HashSet<String> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001434 if (set == null) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001435 set = new HashSet<String>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001436 mBackupParticipants.put(uid, set);
1437 }
Christopher Tatea3d55342012-03-27 13:16:18 -07001438 set.add(pkg.packageName);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001439 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001440
Christopher Tatee82f68d2012-10-23 15:07:38 -07001441 // Schedule a backup for it on general principles
1442 if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1443 dataChangedImpl(pkg.packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001444 }
Christopher Tate487529a2009-04-29 14:03:25 -07001445 }
1446 }
1447
Christopher Tate0bacfd22012-01-11 14:41:19 -08001448 // Remove the given packages' entries from our known active set.
Christopher Tatea3d55342012-03-27 13:16:18 -07001449 void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001450 if (packageNames == null) {
1451 Slog.w(TAG, "removePackageParticipants with null list");
1452 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001453 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001454
Christopher Tatea3d55342012-03-27 13:16:18 -07001455 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1456 + " #" + packageNames.length);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001457 for (String pkg : packageNames) {
Christopher Tatea3d55342012-03-27 13:16:18 -07001458 // Known previous UID, so we know which package set to check
1459 HashSet<String> set = mBackupParticipants.get(oldUid);
1460 if (set != null && set.contains(pkg)) {
1461 removePackageFromSetLocked(set, pkg);
1462 if (set.isEmpty()) {
1463 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set");
1464 mBackupParticipants.remove(oldUid);
1465 }
1466 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001467 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001468 }
1469
Christopher Tatea3d55342012-03-27 13:16:18 -07001470 private void removePackageFromSetLocked(final HashSet<String> set,
1471 final String packageName) {
1472 if (set.contains(packageName)) {
1473 // Found it. Remove this one package from the bookkeeping, and
1474 // if it's the last participating app under this uid we drop the
1475 // (now-empty) set as well.
Christopher Tatee82f68d2012-10-23 15:07:38 -07001476 // Note that we deliberately leave it 'known' in the "ever backed up"
1477 // bookkeeping so that its current-dataset data will be retrieved
1478 // if the app is subsequently reinstalled
Christopher Tatea3d55342012-03-27 13:16:18 -07001479 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName);
Christopher Tatea3d55342012-03-27 13:16:18 -07001480 set.remove(packageName);
Christopher Tate346acb12012-10-15 19:20:25 -07001481 mPendingBackups.remove(packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001482 }
1483 }
1484
Christopher Tate181fafa2009-05-14 11:12:14 -07001485 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001486 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001487 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001488 int flags = PackageManager.GET_SIGNATURES;
1489 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1490 int N = packages.size();
1491 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001492 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001493 try {
1494 ApplicationInfo app = pkg.applicationInfo;
1495 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001496 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001497 packages.remove(a);
1498 }
1499 else {
1500 // we will need the shared library path, so look that up and store it here
1501 app = mPackageManager.getApplicationInfo(pkg.packageName,
1502 PackageManager.GET_SHARED_LIBRARY_FILES);
1503 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1504 }
1505 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001506 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001507 }
1508 }
Dan Egnorefe52642009-06-24 00:16:33 -07001509 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001510 }
Christopher Tateaa088442009-06-16 18:25:46 -07001511
Christopher Tate84725812010-02-04 15:52:40 -08001512 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001513 // backed up at least once
1514 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001515 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1516
1517 synchronized (mEverStoredApps) {
1518 if (!mEverStoredApps.add(packageName)) return;
1519
1520 RandomAccessFile out = null;
1521 try {
1522 out = new RandomAccessFile(mEverStored, "rws");
1523 out.seek(out.length());
1524 out.writeUTF(packageName);
1525 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001526 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001527 } finally {
1528 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001529 }
1530 }
1531 }
1532
Christopher Tatee97e8072009-07-15 16:45:50 -07001533 // Remove our awareness of having ever backed up the given package
1534 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001535 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1536 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001537
Dan Egnor852f8e42009-09-30 11:20:45 -07001538 synchronized (mEverStoredApps) {
1539 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1540 // we'll recognize on initialization time that the package no longer
1541 // exists and fix it up then.
1542 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1543 RandomAccessFile known = null;
1544 try {
1545 known = new RandomAccessFile(tempKnownFile, "rws");
1546 mEverStoredApps.remove(packageName);
1547 for (String s : mEverStoredApps) {
1548 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001549 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001550 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001551 known.close();
1552 known = null;
1553 if (!tempKnownFile.renameTo(mEverStored)) {
1554 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1555 }
1556 } catch (IOException e) {
1557 // Bad: we couldn't create the new copy. For safety's sake we
1558 // abandon the whole process and remove all what's-backed-up
1559 // state entirely, meaning we'll force a backup pass for every
1560 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001561 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001562 mEverStoredApps.clear();
1563 tempKnownFile.delete();
1564 mEverStored.delete();
1565 } finally {
1566 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001567 }
1568 }
1569 }
1570
Christopher Tateb49ceb32010-02-08 16:22:24 -08001571 // Persistently record the current and ancestral backup tokens as well
1572 // as the set of packages with data [supposedly] available in the
1573 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001574 void writeRestoreTokens() {
1575 try {
1576 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001577
1578 // First, the version number of this record, for futureproofing
1579 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1580
1581 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001582 af.writeLong(mAncestralToken);
1583 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001584
1585 // Now write the set of ancestral packages
1586 if (mAncestralPackages == null) {
1587 af.writeInt(-1);
1588 } else {
1589 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001590 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001591 for (String pkgName : mAncestralPackages) {
1592 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001593 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001594 }
1595 }
Christopher Tate84725812010-02-04 15:52:40 -08001596 af.close();
1597 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001598 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001599 }
1600 }
1601
Dan Egnor87a02bc2009-06-17 02:30:10 -07001602 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001603 private IBackupTransport getTransport(String transportName) {
1604 synchronized (mTransports) {
1605 IBackupTransport transport = mTransports.get(transportName);
1606 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001607 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001608 }
1609 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001610 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001611 }
1612
Christopher Tatedf01dea2009-06-09 20:45:02 -07001613 // fire off a backup agent, blocking until it attaches or times out
1614 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1615 IBackupAgent agent = null;
1616 synchronized(mAgentConnectLock) {
1617 mConnecting = true;
1618 mConnectedAgent = null;
1619 try {
1620 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001622
1623 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001624 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1626 while (mConnecting && mConnectedAgent == null
1627 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001629 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001630 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001631 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001632 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tate346acb12012-10-15 19:20:25 -07001633 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 return null;
1635 }
1636 }
1637
1638 // if we timed out with no connect, abort and move on
1639 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tate346acb12012-10-15 19:20:25 -07001641 mActivityManager.clearPendingBackup();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001642 return null;
1643 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001644 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001645 agent = mConnectedAgent;
1646 }
1647 } catch (RemoteException e) {
1648 // can't happen
1649 }
1650 }
1651 return agent;
1652 }
1653
Christopher Tatec7b31e32009-06-10 15:49:30 -07001654 // clear an application's data, blocking until the operation completes or times out
1655 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001656 // Don't wipe packages marked allowClearUserData=false
1657 try {
1658 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1659 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001660 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001661 + packageName);
1662 return;
1663 }
1664 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001665 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001666 return;
1667 }
1668
Christopher Tatec7b31e32009-06-10 15:49:30 -07001669 ClearDataObserver observer = new ClearDataObserver();
1670
1671 synchronized(mClearDataLock) {
1672 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001673 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001674 mActivityManager.clearApplicationUserData(packageName, observer, 0);
Christopher Tate9dfdac52009-08-06 14:57:53 -07001675 } catch (RemoteException e) {
1676 // can't happen because the activity manager is in this process
1677 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001678
1679 // only wait 10 seconds for the clear data to happen
1680 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1681 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1682 try {
1683 mClearDataLock.wait(5000);
1684 } catch (InterruptedException e) {
1685 // won't happen, but still.
1686 mClearingData = false;
1687 }
1688 }
1689 }
1690 }
1691
1692 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001693 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001694 synchronized(mClearDataLock) {
1695 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001696 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001697 }
1698 }
1699 }
1700
Christopher Tate1bb69062010-02-19 17:02:12 -08001701 // Get the restore-set token for the best-available restore set for this package:
1702 // the active set if possible, else the ancestral one. Returns zero if none available.
1703 long getAvailableRestoreToken(String packageName) {
1704 long token = mAncestralToken;
1705 synchronized (mQueueLock) {
1706 if (mEverStoredApps.contains(packageName)) {
1707 token = mCurrentToken;
1708 }
1709 }
1710 return token;
1711 }
1712
Christopher Tate44a27902010-01-27 17:15:49 -08001713 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001714 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1715
1716 interface BackupRestoreTask {
1717 // Execute one tick of whatever state machine the task implements
1718 void execute();
1719
1720 // An operation that wanted a callback has completed
1721 void operationComplete();
1722
1723 // An operation that wanted a callback has timed out
1724 void handleTimeout();
1725 }
1726
1727 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1728 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1729 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001730 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001731 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1732
1733 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1734 mBackupHandler.sendMessageDelayed(msg, interval);
1735 }
1736 }
1737
1738 // synchronous waiter case
1739 boolean waitUntilOperationComplete(int token) {
1740 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1741 + Integer.toHexString(token));
1742 int finalState = OP_PENDING;
1743 Operation op = null;
1744 synchronized (mCurrentOpLock) {
1745 while (true) {
1746 op = mCurrentOperations.get(token);
1747 if (op == null) {
1748 // mysterious disappearance: treat as success with no callback
1749 break;
1750 } else {
1751 if (op.state == OP_PENDING) {
1752 try {
1753 mCurrentOpLock.wait();
1754 } catch (InterruptedException e) {}
1755 // When the wait is notified we loop around and recheck the current state
1756 } else {
1757 // No longer pending; we're done
1758 finalState = op.state;
1759 break;
1760 }
Christopher Tate44a27902010-01-27 17:15:49 -08001761 }
Christopher Tate44a27902010-01-27 17:15:49 -08001762 }
1763 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001764
Christopher Tate44a27902010-01-27 17:15:49 -08001765 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001766 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001767 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001768 return finalState == OP_ACKNOWLEDGED;
1769 }
1770
Christopher Tate8e294d42011-08-31 20:37:12 -07001771 void handleTimeout(int token, Object obj) {
1772 // Notify any synchronous waiters
1773 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001774 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001775 op = mCurrentOperations.get(token);
1776 if (MORE_DEBUG) {
1777 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1778 + " but no op found");
1779 }
1780 int state = (op != null) ? op.state : OP_TIMEOUT;
1781 if (state == OP_PENDING) {
1782 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1783 op.state = OP_TIMEOUT;
1784 mCurrentOperations.put(token, op);
1785 }
1786 mCurrentOpLock.notifyAll();
1787 }
1788
1789 // If there's a TimeoutHandler for this event, call it
1790 if (op != null && op.callback != null) {
1791 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001792 }
Christopher Tate44a27902010-01-27 17:15:49 -08001793 }
1794
Christopher Tate043dadc2009-06-02 16:11:00 -07001795 // ----- Back up a set of applications via a worker thread -----
1796
Christopher Tate8e294d42011-08-31 20:37:12 -07001797 enum BackupState {
1798 INITIAL,
1799 RUNNING_QUEUE,
1800 FINAL
1801 }
1802
1803 class PerformBackupTask implements BackupRestoreTask {
1804 private static final String TAG = "PerformBackupTask";
1805
Christopher Tateaa088442009-06-16 18:25:46 -07001806 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001807 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001808 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001809 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001810 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001811 BackupState mCurrentState;
1812
1813 // carried information about the current in-flight operation
1814 PackageInfo mCurrentPackage;
1815 File mSavedStateName;
1816 File mBackupDataName;
1817 File mNewStateName;
1818 ParcelFileDescriptor mSavedState;
1819 ParcelFileDescriptor mBackupData;
1820 ParcelFileDescriptor mNewState;
1821 int mStatus;
1822 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001823
Christopher Tate44a27902010-01-27 17:15:49 -08001824 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001825 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001826 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001827 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001828 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001829
1830 try {
1831 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1832 } catch (RemoteException e) {
1833 // can't happen; the transport is local
1834 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001835
1836 mCurrentState = BackupState.INITIAL;
1837 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001838
1839 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001840 }
1841
Christopher Tate8e294d42011-08-31 20:37:12 -07001842 // Main entry point: perform one chunk of work, updating the state as appropriate
1843 // and reposting the next chunk to the primary backup handler thread.
1844 @Override
1845 public void execute() {
1846 switch (mCurrentState) {
1847 case INITIAL:
1848 beginBackup();
1849 break;
1850
1851 case RUNNING_QUEUE:
1852 invokeNextAgent();
1853 break;
1854
1855 case FINAL:
1856 if (!mFinished) finalizeBackup();
1857 else {
1858 Slog.e(TAG, "Duplicate finish");
1859 }
Christopher Tate2982d062011-09-06 20:35:24 -07001860 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001861 break;
1862 }
1863 }
1864
1865 // We're starting a backup pass. Initialize the transport and send
1866 // the PM metadata blob if we haven't already.
1867 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001868 if (DEBUG_BACKUP_TRACE) {
1869 clearBackupTrace();
1870 StringBuilder b = new StringBuilder(256);
1871 b.append("beginBackup: [");
1872 for (BackupRequest req : mOriginalQueue) {
1873 b.append(' ');
1874 b.append(req.packageName);
1875 }
1876 b.append(" ]");
1877 addBackupTrace(b.toString());
1878 }
1879
Christopher Tate8e294d42011-08-31 20:37:12 -07001880 mStatus = BackupConstants.TRANSPORT_OK;
1881
1882 // Sanity check: if the queue is empty we have no work to do.
1883 if (mOriginalQueue.isEmpty()) {
1884 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001885 addBackupTrace("queue empty at begin");
1886 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001887 return;
1888 }
1889
1890 // We need to retain the original queue contents in case of transport
1891 // failure, but we want a working copy that we can manipulate along
1892 // the way.
1893 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1894
Joe Onorato8a9b2202010-02-26 18:56:32 -08001895 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001896
Christopher Tate8e294d42011-08-31 20:37:12 -07001897 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001898 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001899 final String transportName = mTransport.transportDirName();
1900 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001901
Dan Egnor852f8e42009-09-30 11:20:45 -07001902 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001903 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001904 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001905 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001906 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001907 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001908
1909 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001910 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001911 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001912 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001913 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001914 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001915 }
Dan Egnor01445162009-09-21 17:04:05 -07001916 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001917
1918 // The package manager doesn't have a proper <application> etc, but since
1919 // it's running here in the system process we can just set up its agent
1920 // directly and use a synthetic BackupRequest. We always run this pass
1921 // because it's cheap and this way we guarantee that we don't get out of
1922 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001923 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001924 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1925 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001926 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001927 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001928 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001929 }
Christopher Tate90967f42009-09-20 15:28:33 -07001930
Christopher Tate8e294d42011-08-31 20:37:12 -07001931 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1932 // The backend reports that our dataset has been wiped. Note this in
1933 // the event log; the no-success code below will reset the backup
1934 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001935 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001936 }
1937 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001938 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001939 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001940 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001941 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001942 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1943 // metadata and its completion/timeout callback will continue the state
1944 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001945 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001946 if (mStatus != BackupConstants.TRANSPORT_OK) {
1947 // if things went wrong at this point, we need to
1948 // restage everything and try again later.
1949 resetBackupState(mStateDir); // Just to make sure.
1950 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001951 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001952 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001953 }
1954
Christopher Tate8e294d42011-08-31 20:37:12 -07001955 // Transport has been initialized and the PM metadata submitted successfully
1956 // if that was warranted. Now we process the single next thing in the queue.
1957 void invokeNextAgent() {
1958 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001959 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001960
Christopher Tate8e294d42011-08-31 20:37:12 -07001961 // Sanity check that we have work to do. If not, skip to the end where
1962 // we reestablish the wakelock invariants etc.
1963 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001964 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001965 executeNextState(BackupState.FINAL);
1966 return;
1967 }
1968
1969 // pop the entry we're going to process on this step
1970 BackupRequest request = mQueue.get(0);
1971 mQueue.remove(0);
1972
1973 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001974 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001975
1976 // Verify that the requested app exists; it might be something that
1977 // requested a backup but was then uninstalled. The request was
1978 // journalled and rather than tamper with the journal it's safer
1979 // to sanity-check here. This also gives us the classname of the
1980 // package's backup agent.
1981 try {
1982 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1983 PackageManager.GET_SIGNATURES);
Christopher Tate9c2efb32012-03-23 13:00:05 -07001984 if (mCurrentPackage.applicationInfo.backupAgentName == null) {
1985 // The manifest has changed but we had a stale backup request pending.
1986 // This won't happen again because the app won't be requesting further
1987 // backups.
1988 Slog.i(TAG, "Package " + request.packageName
1989 + " no longer supports backup; skipping");
1990 addBackupTrace("skipping - no agent, completion is noop");
1991 executeNextState(BackupState.RUNNING_QUEUE);
1992 return;
1993 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001994
Christopher Tate043dadc2009-06-02 16:11:00 -07001995 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001996 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1998 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001999 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002000 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07002001 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002002 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2003 // at this point we'll either get a completion callback from the
2004 // agent, or a timeout message on the main handler. either way, we're
2005 // done here as long as we're successful so far.
2006 } else {
2007 // Timeout waiting for the agent
2008 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002009 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002010 } catch (SecurityException ex) {
2011 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002012 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002013 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002014 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002015 }
2016 } catch (NameNotFoundException e) {
2017 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002018 addBackupTrace("no such package");
2019 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002020 } finally {
2021 mWakelock.setWorkSource(null);
2022
2023 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002024 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002025 if (mStatus != BackupConstants.TRANSPORT_OK) {
2026 BackupState nextState = BackupState.RUNNING_QUEUE;
2027
2028 // An agent-level failure means we reenqueue this one agent for
2029 // a later retry, but otherwise proceed normally.
2030 if (mStatus == BackupConstants.AGENT_ERROR) {
2031 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2032 + " - restaging");
2033 dataChangedImpl(request.packageName);
2034 mStatus = BackupConstants.TRANSPORT_OK;
2035 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002036 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2037 // Failed lookup of the app, so we couldn't bring up an agent, but
2038 // we're otherwise fine. Just drop it and go on to the next as usual.
2039 mStatus = BackupConstants.TRANSPORT_OK;
2040 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002041 // Transport-level failure means we reenqueue everything
2042 revertAndEndBackup();
2043 nextState = BackupState.FINAL;
2044 }
2045
2046 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002047 } else {
2048 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002049 }
2050 }
2051 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002052
Christopher Tate8e294d42011-08-31 20:37:12 -07002053 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002054 addBackupTrace("finishing");
2055
Christopher Tate8e294d42011-08-31 20:37:12 -07002056 // Either backup was successful, in which case we of course do not need
2057 // this pass's journal any more; or it failed, in which case we just
2058 // re-enqueued all of these packages in the current active journal.
2059 // Either way, we no longer need this pass's journal.
2060 if (mJournal != null && !mJournal.delete()) {
2061 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2062 }
2063
2064 // If everything actually went through and this is the first time we've
2065 // done a backup, we can now record what the current backup dataset token
2066 // is.
2067 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002068 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002069 try {
2070 mCurrentToken = mTransport.getCurrentRestoreSet();
2071 } catch (RemoteException e) {} // can't happen
2072 writeRestoreTokens();
2073 }
2074
Christopher Tate336a6492011-10-05 16:05:43 -07002075 // Set up the next backup pass - at this point we can set mBackupRunning
2076 // to false to allow another pass to fire, because we're done with the
2077 // state machine sequence and the wakelock is refcounted.
2078 synchronized (mQueueLock) {
2079 mBackupRunning = false;
2080 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002081 // Make sure we back up everything and perform the one-time init
2082 clearMetadata();
2083 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002084 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002085 backupNow();
2086 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002087 }
2088
2089 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002090 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002091 Slog.i(TAG, "Backup pass finished.");
2092 mWakelock.release();
2093 }
2094
Christopher Tatee659fb92011-10-10 16:34:50 -07002095 // Remove the PM metadata state. This will generate an init on the next pass.
2096 void clearMetadata() {
2097 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2098 if (pmState.exists()) pmState.delete();
2099 }
2100
Christopher Tate8e294d42011-08-31 20:37:12 -07002101 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2102 // handler in case it doesn't get back to us.
2103 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002104 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002105 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2106 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002107
Christopher Tate8e294d42011-08-31 20:37:12 -07002108 mSavedStateName = new File(mStateDir, packageName);
2109 mBackupDataName = new File(mDataDir, packageName + ".data");
2110 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111
Christopher Tate8e294d42011-08-31 20:37:12 -07002112 mSavedState = null;
2113 mBackupData = null;
2114 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002115
Christopher Tate4a627c72011-04-01 14:43:32 -07002116 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002117 try {
2118 // Look up the package info & signatures. This is first so that if it
2119 // throws an exception, there's no file setup yet that would need to
2120 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002121 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002122 // The metadata 'package' is synthetic; construct one and make
2123 // sure our global state is pointed at it
2124 mCurrentPackage = new PackageInfo();
2125 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002126 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002127
Christopher Tatec7b31e32009-06-10 15:49:30 -07002128 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002129 // the saved-state "file". This is by definition an incremental,
2130 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002131 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002132 ParcelFileDescriptor.MODE_READ_ONLY |
2133 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002134
Christopher Tate8e294d42011-08-31 20:37:12 -07002135 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002136 ParcelFileDescriptor.MODE_READ_WRITE |
2137 ParcelFileDescriptor.MODE_CREATE |
2138 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002139
rpcraigebab0ae2012-12-04 09:37:23 -05002140 if (!SELinux.restorecon(mBackupDataName)) {
2141 Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2142 }
2143
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002145 ParcelFileDescriptor.MODE_READ_WRITE |
2146 ParcelFileDescriptor.MODE_CREATE |
2147 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002148
Christopher Tate44a27902010-01-27 17:15:49 -08002149 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002150 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002151 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002152 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002153 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002154 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002155 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002156 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002157 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2158 e.toString());
2159 agentErrorCleanup();
2160 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002161 }
2162
Christopher Tate8e294d42011-08-31 20:37:12 -07002163 // At this point the agent is off and running. The next thing to happen will
2164 // either be a callback from the agent, at which point we'll process its data
2165 // for transport, or a timeout. Either way the next phase will happen in
2166 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002167 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002168 return BackupConstants.TRANSPORT_OK;
2169 }
2170
2171 @Override
2172 public void operationComplete() {
2173 // Okay, the agent successfully reported back to us. Spin the data off to the
2174 // transport and proceed with the next stage.
2175 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2176 + mCurrentPackage.packageName);
2177 mBackupHandler.removeMessages(MSG_TIMEOUT);
2178 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002179 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002180
2181 ParcelFileDescriptor backupData = null;
2182 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002183 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002184 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002185 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002186 if (mStatus == BackupConstants.TRANSPORT_OK) {
2187 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002188 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002191 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002192
Dan Egnor83861e72009-09-17 16:17:55 -07002193 // TODO - We call finishBackup() for each application backed up, because
2194 // we need to know now whether it succeeded or failed. Instead, we should
2195 // hold off on finishBackup() until the end, which implies holding off on
2196 // renaming *all* the output state files (see below) until that happens.
2197
Christopher Tate6de74ff2012-01-17 15:20:32 -08002198 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002199 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002200 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002201 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002202 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002203 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002204 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002205 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002206 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002207 }
2208
2209 // After successful transport, delete the now-stale data
2210 // and juggle the files so that next time we supply the agent
2211 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002212 if (mStatus == BackupConstants.TRANSPORT_OK) {
2213 mBackupDataName.delete();
2214 mNewStateName.renameTo(mSavedStateName);
2215 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2216 mCurrentPackage.packageName, size);
2217 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002218 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002219 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2220 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002221 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002222 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002223 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2224 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2225 mCurrentPackage.packageName);
2226 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002227 } finally {
2228 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002229 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002230
Christopher Tate8e294d42011-08-31 20:37:12 -07002231 // If we encountered an error here it's a transport-level failure. That
2232 // means we need to halt everything and reschedule everything for next time.
2233 final BackupState nextState;
2234 if (mStatus != BackupConstants.TRANSPORT_OK) {
2235 revertAndEndBackup();
2236 nextState = BackupState.FINAL;
2237 } else {
2238 // Success! Proceed with the next app if any, otherwise we're done.
2239 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2240 }
2241
2242 executeNextState(nextState);
2243 }
2244
2245 @Override
2246 public void handleTimeout() {
2247 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2248 // it for the next time we run a backup pass.
2249 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2250 // fail repeatedly (i.e. have proved themselves to be buggy).
2251 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2252 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2253 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002254 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002255 agentErrorCleanup();
2256 dataChangedImpl(mCurrentPackage.packageName);
2257 }
2258
2259 void revertAndEndBackup() {
2260 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002261 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002262 for (BackupRequest request : mOriginalQueue) {
2263 dataChangedImpl(request.packageName);
2264 }
2265 // We also want to reset the backup schedule based on whatever
2266 // the transport suggests by way of retry/backoff time.
2267 restartBackupAlarm();
2268 }
2269
2270 void agentErrorCleanup() {
2271 mBackupDataName.delete();
2272 mNewStateName.delete();
2273 clearAgentState();
2274
2275 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2276 }
2277
2278 // Cleanup common to both success and failure cases
2279 void clearAgentState() {
2280 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2281 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2282 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2283 mSavedState = mBackupData = mNewState = null;
2284 synchronized (mCurrentOpLock) {
2285 mCurrentOperations.clear();
2286 }
2287
2288 // If this was a pseudopackage there's no associated Activity Manager state
2289 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002290 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002291 try { // unbind even on timeout, just in case
2292 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2293 } catch (RemoteException e) {}
2294 }
2295 }
2296
2297 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002298 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002299 synchronized (mQueueLock) {
2300 try {
2301 startBackupAlarmsLocked(mTransport.requestBackupTime());
2302 } catch (RemoteException e) { /* cannot happen */ }
2303 }
2304 }
2305
2306 void executeNextState(BackupState nextState) {
2307 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2308 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002309 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002310 mCurrentState = nextState;
2311 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2312 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002313 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002314 }
2315
Christopher Tatedf01dea2009-06-09 20:45:02 -07002316
Christopher Tate4a627c72011-04-01 14:43:32 -07002317 // ----- Full backup to a file/socket -----
2318
2319 class PerformFullBackupTask implements Runnable {
2320 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002321 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002322 IFullBackupRestoreObserver mObserver;
2323 boolean mIncludeApks;
2324 boolean mIncludeShared;
2325 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002326 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002327 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002328 String mCurrentPassword;
2329 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002330 AtomicBoolean mLatchObject;
2331 File mFilesDir;
2332 File mManifestFile;
2333
Christopher Tate7926a692011-07-11 11:31:57 -07002334 class FullBackupRunner implements Runnable {
2335 PackageInfo mPackage;
2336 IBackupAgent mAgent;
2337 ParcelFileDescriptor mPipe;
2338 int mToken;
2339 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002340 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002341
2342 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002343 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002344 mPackage = pack;
2345 mAgent = agent;
2346 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2347 mToken = token;
2348 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002349 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002350 }
2351
2352 @Override
2353 public void run() {
2354 try {
2355 BackupDataOutput output = new BackupDataOutput(
2356 mPipe.getFileDescriptor());
2357
Christopher Tate73d73692012-01-20 17:11:31 -08002358 if (mWriteManifest) {
2359 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2360 writeAppManifest(mPackage, mManifestFile, mSendApk);
2361 FullBackup.backupToTar(mPackage.packageName, null, null,
2362 mFilesDir.getAbsolutePath(),
2363 mManifestFile.getAbsolutePath(),
2364 output);
2365 }
Christopher Tate7926a692011-07-11 11:31:57 -07002366
2367 if (mSendApk) {
2368 writeApkToBackup(mPackage, output);
2369 }
2370
Christopher Tatec58efa62011-08-01 19:20:14 -07002371 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002372 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002373 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2374 } catch (IOException e) {
2375 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2376 } catch (RemoteException e) {
2377 Slog.e(TAG, "Remote agent vanished during full backup of "
2378 + mPackage.packageName);
2379 } finally {
2380 try {
2381 mPipe.close();
2382 } catch (IOException e) {}
2383 }
2384 }
2385 }
2386
Christopher Tate4a627c72011-04-01 14:43:32 -07002387 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002388 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002389 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002390 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002391 mOutputFile = fd;
2392 mObserver = observer;
2393 mIncludeApks = includeApks;
2394 mIncludeShared = includeShared;
2395 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002396 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002397 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002398 mCurrentPassword = curPassword;
2399 // when backing up, if there is a current backup password, we require that
2400 // the user use a nonempty encryption password as well. if one is supplied
2401 // in the UI we use that, but if the UI was left empty we fall back to the
2402 // current backup password (which was supplied by the user as well).
2403 if (encryptPassword == null || "".equals(encryptPassword)) {
2404 mEncryptPassword = curPassword;
2405 } else {
2406 mEncryptPassword = encryptPassword;
2407 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002408 mLatchObject = latch;
2409
2410 mFilesDir = new File("/data/system");
2411 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2412 }
2413
2414 @Override
2415 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002416 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002417
Christopher Tateb0628bf2011-06-02 15:08:13 -07002418 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002419 sendStartBackup();
2420
2421 // doAllApps supersedes the package set if any
2422 if (mAllApps) {
2423 packagesToBackup = mPackageManager.getInstalledPackages(
2424 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002425 // Exclude system apps if we've been asked to do so
2426 if (mIncludeSystem == false) {
2427 for (int i = 0; i < packagesToBackup.size(); ) {
2428 PackageInfo pkg = packagesToBackup.get(i);
2429 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2430 packagesToBackup.remove(i);
2431 } else {
2432 i++;
2433 }
2434 }
2435 }
2436 }
2437
2438 // Now process the command line argument packages, if any. Note that explicitly-
2439 // named system-partition packages will be included even if includeSystem was
2440 // set to false.
2441 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002442 for (String pkgName : mPackages) {
2443 try {
2444 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2445 PackageManager.GET_SIGNATURES));
2446 } catch (NameNotFoundException e) {
2447 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2448 }
2449 }
2450 }
2451
Christopher Tate73d73692012-01-20 17:11:31 -08002452 // Cull any packages that have indicated that backups are not permitted, as well
2453 // as any explicit mention of the 'special' shared-storage agent package (we
2454 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002455 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002456 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002457 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2458 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002459 packagesToBackup.remove(i);
2460 } else {
2461 i++;
2462 }
2463 }
2464
Christopher Tatef6d6fa82012-09-26 15:25:59 -07002465 // Cull any packages that run as system-domain uids but do not define their
2466 // own backup agents
2467 for (int i = 0; i < packagesToBackup.size(); ) {
2468 PackageInfo pkg = packagesToBackup.get(i);
2469 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2470 && (pkg.applicationInfo.backupAgentName == null)) {
2471 if (MORE_DEBUG) {
2472 Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2473 }
2474 packagesToBackup.remove(i);
2475 } else {
2476 i++;
2477 }
2478 }
2479
Christopher Tate7926a692011-07-11 11:31:57 -07002480 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002481 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002482
Christopher Tate4a627c72011-04-01 14:43:32 -07002483 PackageInfo pkg = null;
2484 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002485 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002486 boolean compressing = COMPRESS_FULL_BACKUPS;
2487 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002488
Christopher Tateeef4ae42011-08-05 13:15:53 -07002489 // Verify that the given password matches the currently-active
2490 // backup password, if any
2491 if (hasBackupPassword()) {
2492 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2493 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2494 return;
2495 }
2496 }
2497
Christopher Tate7bdb0962011-07-13 19:30:21 -07002498 // Write the global file header. All strings are UTF-8 encoded; lines end
2499 // with a '\n' byte. Actual backup data begins immediately following the
2500 // final '\n'.
2501 //
2502 // line 1: "ANDROID BACKUP"
2503 // line 2: backup file format version, currently "1"
2504 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002505 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2506 //
2507 // When line 4 is not "none", then additional header data follows:
2508 //
2509 // line 5: user password salt [hex]
2510 // line 6: master key checksum salt [hex]
2511 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2512 // line 8: IV of the user key [hex]
2513 // line 9: master key blob [hex]
2514 // IV of the master key, master key itself, master key checksum hash
2515 //
2516 // The master key checksum is the master key plus its checksum salt, run through
2517 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2518 // correct password for decrypting the archive: the master key decrypted from
2519 // the archive using the user-supplied password is also run through PBKDF2 in
2520 // this way, and if the result does not match the checksum as stored in the
2521 // archive, then we know that the user-supplied password does not match the
2522 // archive's.
2523 StringBuilder headerbuf = new StringBuilder(1024);
2524
Christopher Tate7bdb0962011-07-13 19:30:21 -07002525 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002526 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2527 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002528
2529 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002530 // Set up the encryption stage if appropriate, and emit the correct header
2531 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002532 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2533 } else {
2534 headerbuf.append("none\n");
2535 }
2536
Christopher Tate7bdb0962011-07-13 19:30:21 -07002537 byte[] header = headerbuf.toString().getBytes("UTF-8");
2538 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002539
2540 // Set up the compression stage feeding into the encryption stage (if any)
2541 if (compressing) {
2542 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2543 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2544 }
2545
2546 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002547 } catch (Exception e) {
2548 // Should never happen!
2549 Slog.e(TAG, "Unable to emit archive header", e);
2550 return;
2551 }
2552
Christopher Tate73d73692012-01-20 17:11:31 -08002553 // Shared storage if requested
2554 if (mIncludeShared) {
2555 try {
2556 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2557 packagesToBackup.add(pkg);
2558 } catch (NameNotFoundException e) {
2559 Slog.e(TAG, "Unable to find shared-storage backup handler");
2560 }
2561 }
2562
Christopher Tateb0628bf2011-06-02 15:08:13 -07002563 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002564 int N = packagesToBackup.size();
2565 for (int i = 0; i < N; i++) {
2566 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002567 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002568 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002569
Christopher Tate6853fcf2011-08-10 17:52:21 -07002570 // Done!
2571 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002572 } catch (RemoteException e) {
2573 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002574 } catch (Exception e) {
2575 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002576 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002577 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002578 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002579 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002580 mOutputFile.close();
2581 } catch (IOException e) {
2582 /* nothing we can do about this */
2583 }
2584 synchronized (mCurrentOpLock) {
2585 mCurrentOperations.clear();
2586 }
2587 synchronized (mLatchObject) {
2588 mLatchObject.set(true);
2589 mLatchObject.notifyAll();
2590 }
2591 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002592 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002593 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002594 }
2595 }
2596
Christopher Tate2efd2db2011-07-19 16:32:49 -07002597 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2598 OutputStream ofstream) throws Exception {
2599 // User key will be used to encrypt the master key.
2600 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002601 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002602 PBKDF2_HASH_ROUNDS);
2603
2604 // the master key is random for each backup
2605 byte[] masterPw = new byte[256 / 8];
2606 mRng.nextBytes(masterPw);
2607 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2608
2609 // primary encryption of the datastream with the random key
2610 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2611 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2612 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2613 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2614
2615 // line 4: name of encryption algorithm
2616 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2617 headerbuf.append('\n');
2618 // line 5: user password salt [hex]
2619 headerbuf.append(byteArrayToHex(newUserSalt));
2620 headerbuf.append('\n');
2621 // line 6: master key checksum salt [hex]
2622 headerbuf.append(byteArrayToHex(checksumSalt));
2623 headerbuf.append('\n');
2624 // line 7: number of PBKDF2 rounds used [decimal]
2625 headerbuf.append(PBKDF2_HASH_ROUNDS);
2626 headerbuf.append('\n');
2627
2628 // line 8: IV of the user key [hex]
2629 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2630 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2631
2632 byte[] IV = mkC.getIV();
2633 headerbuf.append(byteArrayToHex(IV));
2634 headerbuf.append('\n');
2635
2636 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2637 // [byte] IV length = Niv
2638 // [array of Niv bytes] IV itself
2639 // [byte] master key length = Nmk
2640 // [array of Nmk bytes] master key itself
2641 // [byte] MK checksum hash length = Nck
2642 // [array of Nck bytes] master key checksum hash
2643 //
2644 // The checksum is the (master key + checksum salt), run through the
2645 // stated number of PBKDF2 rounds
2646 IV = c.getIV();
2647 byte[] mk = masterKeySpec.getEncoded();
2648 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2649 checksumSalt, PBKDF2_HASH_ROUNDS);
2650
2651 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2652 + checksum.length + 3);
2653 DataOutputStream mkOut = new DataOutputStream(blob);
2654 mkOut.writeByte(IV.length);
2655 mkOut.write(IV);
2656 mkOut.writeByte(mk.length);
2657 mkOut.write(mk);
2658 mkOut.writeByte(checksum.length);
2659 mkOut.write(checksum);
2660 mkOut.flush();
2661 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2662 headerbuf.append(byteArrayToHex(encryptedMk));
2663 headerbuf.append('\n');
2664
2665 return finalOutput;
2666 }
2667
2668 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002669 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002670 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2671
2672 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2673 IApplicationThread.BACKUP_MODE_FULL);
2674 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002675 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002676 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002677 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002678
Christopher Tateb0628bf2011-06-02 15:08:13 -07002679 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002680 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002681 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002682 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002683 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2684 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2685 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2686
Christopher Tate73d73692012-01-20 17:11:31 -08002687 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002688
Christopher Tate7926a692011-07-11 11:31:57 -07002689 final int token = generateToken();
2690 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002691 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002692 pipes[1].close(); // the runner has dup'd it
2693 pipes[1] = null;
2694 Thread t = new Thread(runner);
2695 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002696
Christopher Tate7926a692011-07-11 11:31:57 -07002697 // Now pull data from the app and stuff it into the compressor
2698 try {
2699 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2700 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002701
Christopher Tate7926a692011-07-11 11:31:57 -07002702 byte[] buffer = new byte[16 * 1024];
2703 int chunkTotal;
2704 while ((chunkTotal = in.readInt()) > 0) {
2705 while (chunkTotal > 0) {
2706 int toRead = (chunkTotal > buffer.length)
2707 ? buffer.length : chunkTotal;
2708 int nRead = in.read(buffer, 0, toRead);
2709 out.write(buffer, 0, nRead);
2710 chunkTotal -= nRead;
2711 }
2712 }
2713 } catch (IOException e) {
2714 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002715 }
2716
Christopher Tateb0628bf2011-06-02 15:08:13 -07002717 if (!waitUntilOperationComplete(token)) {
2718 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2719 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002720 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002721 }
Christopher Tate7926a692011-07-11 11:31:57 -07002722
Christopher Tateb0628bf2011-06-02 15:08:13 -07002723 } catch (IOException e) {
2724 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002725 } finally {
2726 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002727 // flush after every package
2728 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002729 if (pipes != null) {
2730 if (pipes[0] != null) pipes[0].close();
2731 if (pipes[1] != null) pipes[1].close();
2732 }
Christopher Tate7926a692011-07-11 11:31:57 -07002733 } catch (IOException e) {
2734 Slog.w(TAG, "Error bringing down backup stack");
2735 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002736 }
2737 } else {
2738 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2739 }
2740 tearDown(pkg);
2741 }
2742
Christopher Tate79ec80d2011-06-24 14:58:49 -07002743 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2744 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2745 final String appSourceDir = pkg.applicationInfo.sourceDir;
2746 final String apkDir = new File(appSourceDir).getParent();
2747 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2748 apkDir, appSourceDir, output);
2749
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002750 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
2751 // doesn't have access to external storage.
2752
Christopher Tate79ec80d2011-06-24 14:58:49 -07002753 // Save associated .obb content if it exists and we did save the apk
2754 // check for .obb and save those too
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002755 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
2756 final File obbDir = userEnv.getExternalStorageAppObbDirectory(pkg.packageName);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002757 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002758 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002759 File[] obbFiles = obbDir.listFiles();
2760 if (obbFiles != null) {
2761 final String obbDirName = obbDir.getAbsolutePath();
2762 for (File obb : obbFiles) {
2763 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2764 obbDirName, obb.getAbsolutePath(), output);
2765 }
2766 }
2767 }
2768 }
2769
Christopher Tate6853fcf2011-08-10 17:52:21 -07002770 private void finalizeBackup(OutputStream out) {
2771 try {
2772 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2773 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2774 out.write(eof);
2775 } catch (IOException e) {
2776 Slog.w(TAG, "Error attempting to finalize backup stream");
2777 }
2778 }
2779
Christopher Tate4a627c72011-04-01 14:43:32 -07002780 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2781 throws IOException {
2782 // Manifest format. All data are strings ending in LF:
2783 // BACKUP_MANIFEST_VERSION, currently 1
2784 //
2785 // Version 1:
2786 // package name
2787 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002788 // platform versionCode
2789 // getInstallerPackageName() for this package (maybe empty)
2790 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002791 // number of signatures == N
2792 // N*: signature byte array in ascii format per Signature.toCharsString()
2793 StringBuilder builder = new StringBuilder(4096);
2794 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2795
2796 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2797 printer.println(pkg.packageName);
2798 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002799 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2800
2801 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2802 printer.println((installerName != null) ? installerName : "");
2803
Christopher Tate4a627c72011-04-01 14:43:32 -07002804 printer.println(withApk ? "1" : "0");
2805 if (pkg.signatures == null) {
2806 printer.println("0");
2807 } else {
2808 printer.println(Integer.toString(pkg.signatures.length));
2809 for (Signature sig : pkg.signatures) {
2810 printer.println(sig.toCharsString());
2811 }
2812 }
2813
2814 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002815 outstream.write(builder.toString().getBytes());
2816 outstream.close();
2817 }
2818
2819 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002820 if (pkg != null) {
2821 final ApplicationInfo app = pkg.applicationInfo;
2822 if (app != null) {
2823 try {
2824 // unbind and tidy up even on timeout or failure, just in case
2825 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002826
Christopher Tateb0628bf2011-06-02 15:08:13 -07002827 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002828 if (app.uid != Process.SYSTEM_UID
2829 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002830 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002831 mActivityManager.killApplicationProcess(app.processName, app.uid);
2832 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002833 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002834 }
2835 } catch (RemoteException e) {
2836 Slog.d(TAG, "Lost app trying to shut down");
2837 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002838 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002839 }
2840 }
2841
2842 // wrappers for observer use
2843 void sendStartBackup() {
2844 if (mObserver != null) {
2845 try {
2846 mObserver.onStartBackup();
2847 } catch (RemoteException e) {
2848 Slog.w(TAG, "full backup observer went away: startBackup");
2849 mObserver = null;
2850 }
2851 }
2852 }
2853
2854 void sendOnBackupPackage(String name) {
2855 if (mObserver != null) {
2856 try {
2857 // TODO: use a more user-friendly name string
2858 mObserver.onBackupPackage(name);
2859 } catch (RemoteException e) {
2860 Slog.w(TAG, "full backup observer went away: backupPackage");
2861 mObserver = null;
2862 }
2863 }
2864 }
2865
2866 void sendEndBackup() {
2867 if (mObserver != null) {
2868 try {
2869 mObserver.onEndBackup();
2870 } catch (RemoteException e) {
2871 Slog.w(TAG, "full backup observer went away: endBackup");
2872 mObserver = null;
2873 }
2874 }
2875 }
2876 }
2877
2878
Christopher Tate75a99702011-05-18 16:28:19 -07002879 // ----- Full restore from a file/socket -----
2880
2881 // Description of a file in the restore datastream
2882 static class FileMetadata {
2883 String packageName; // name of the owning app
2884 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002885 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002886 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2887 String path; // subpath within the semantic domain
2888 long mode; // e.g. 0666 (actually int)
2889 long mtime; // last mod time, UTC time_t (actually int)
2890 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002891
2892 @Override
2893 public String toString() {
2894 StringBuilder sb = new StringBuilder(128);
2895 sb.append("FileMetadata{");
2896 sb.append(packageName); sb.append(',');
2897 sb.append(type); sb.append(',');
2898 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2899 sb.append(size);
2900 sb.append('}');
2901 return sb.toString();
2902 }
Christopher Tate75a99702011-05-18 16:28:19 -07002903 }
2904
2905 enum RestorePolicy {
2906 IGNORE,
2907 ACCEPT,
2908 ACCEPT_IF_APK
2909 }
2910
2911 class PerformFullRestoreTask implements Runnable {
2912 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002913 String mCurrentPassword;
2914 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002915 IFullBackupRestoreObserver mObserver;
2916 AtomicBoolean mLatchObject;
2917 IBackupAgent mAgent;
2918 String mAgentPackage;
2919 ApplicationInfo mTargetApp;
2920 ParcelFileDescriptor[] mPipes = null;
2921
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002922 long mBytes;
2923
Christopher Tate75a99702011-05-18 16:28:19 -07002924 // possible handling states for a given package in the restore dataset
2925 final HashMap<String, RestorePolicy> mPackagePolicies
2926 = new HashMap<String, RestorePolicy>();
2927
2928 // installer package names for each encountered app, derived from the manifests
2929 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2930
2931 // Signatures for a given package found in its manifest file
2932 final HashMap<String, Signature[]> mManifestSignatures
2933 = new HashMap<String, Signature[]>();
2934
2935 // Packages we've already wiped data on when restoring their first file
2936 final HashSet<String> mClearedPackages = new HashSet<String>();
2937
Christopher Tate728a1c42011-07-28 18:03:03 -07002938 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002939 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002940 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002941 mCurrentPassword = curPassword;
2942 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002943 mObserver = observer;
2944 mLatchObject = latch;
2945 mAgent = null;
2946 mAgentPackage = null;
2947 mTargetApp = null;
2948
2949 // Which packages we've already wiped data on. We prepopulate this
2950 // with a whitelist of packages known to be unclearable.
2951 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002952 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002953
Christopher Tate75a99702011-05-18 16:28:19 -07002954 }
2955
2956 class RestoreFileRunnable implements Runnable {
2957 IBackupAgent mAgent;
2958 FileMetadata mInfo;
2959 ParcelFileDescriptor mSocket;
2960 int mToken;
2961
2962 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2963 ParcelFileDescriptor socket, int token) throws IOException {
2964 mAgent = agent;
2965 mInfo = info;
2966 mToken = token;
2967
2968 // This class is used strictly for process-local binder invocations. The
2969 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2970 // do not automatically get a 'dup'ed descriptor that we can can continue
2971 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2972 // before proceeding to do the restore.
2973 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2974 }
2975
2976 @Override
2977 public void run() {
2978 try {
2979 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2980 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2981 mToken, mBackupManagerBinder);
2982 } catch (RemoteException e) {
2983 // never happens; this is used strictly for local binder calls
2984 }
2985 }
2986 }
2987
2988 @Override
2989 public void run() {
2990 Slog.i(TAG, "--- Performing full-dataset restore ---");
2991 sendStartRestore();
2992
Christopher Tateb0628bf2011-06-02 15:08:13 -07002993 // Are we able to restore shared-storage data?
2994 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002995 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002996 }
2997
Christopher Tate2efd2db2011-07-19 16:32:49 -07002998 FileInputStream rawInStream = null;
2999 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07003000 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07003001 if (hasBackupPassword()) {
3002 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
3003 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3004 return;
3005 }
3006 }
3007
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003008 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07003009 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003010 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3011 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003012
3013 // First, parse out the unencrypted/uncompressed header
3014 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003015 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07003016 final InputStream in;
3017
3018 boolean okay = false;
3019 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3020 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003021 rawDataIn.readFully(streamHeader);
3022 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3023 if (Arrays.equals(magicBytes, streamHeader)) {
3024 // okay, header looks good. now parse out the rest of the fields.
3025 String s = readHeaderLine(rawInStream);
3026 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3027 // okay, it's a version we recognize
3028 s = readHeaderLine(rawInStream);
3029 compressed = (Integer.parseInt(s) != 0);
3030 s = readHeaderLine(rawInStream);
3031 if (s.equals("none")) {
3032 // no more header to parse; we're good to go
3033 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003034 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003035 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3036 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003037 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003038 }
3039 } else Slog.w(TAG, "Archive is encrypted but no password given");
3040 } else Slog.w(TAG, "Wrong header version: " + s);
3041 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003042
3043 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003044 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003045 return;
3046 }
3047
3048 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003049 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003050
3051 boolean didRestore;
3052 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003053 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003054 } while (didRestore);
3055
Christopher Tatec58efa62011-08-01 19:20:14 -07003056 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003057 } catch (IOException e) {
3058 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003059 } finally {
3060 tearDownPipes();
3061 tearDownAgent(mTargetApp);
3062
3063 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003064 if (rawDataIn != null) rawDataIn.close();
3065 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003066 mInputFile.close();
3067 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003068 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003069 /* nothing we can do about this */
3070 }
3071 synchronized (mCurrentOpLock) {
3072 mCurrentOperations.clear();
3073 }
3074 synchronized (mLatchObject) {
3075 mLatchObject.set(true);
3076 mLatchObject.notifyAll();
3077 }
3078 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003079 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003080 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003081 }
3082 }
3083
Christopher Tate7bdb0962011-07-13 19:30:21 -07003084 String readHeaderLine(InputStream in) throws IOException {
3085 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003086 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003087 while ((c = in.read()) >= 0) {
3088 if (c == '\n') break; // consume and discard the newlines
3089 buffer.append((char)c);
3090 }
3091 return buffer.toString();
3092 }
3093
Christopher Tate2efd2db2011-07-19 16:32:49 -07003094 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3095 InputStream result = null;
3096 try {
3097 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3098
3099 String userSaltHex = readHeaderLine(rawInStream); // 5
3100 byte[] userSalt = hexToByteArray(userSaltHex);
3101
3102 String ckSaltHex = readHeaderLine(rawInStream); // 6
3103 byte[] ckSalt = hexToByteArray(ckSaltHex);
3104
3105 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3106 String userIvHex = readHeaderLine(rawInStream); // 8
3107
3108 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3109
3110 // decrypt the master key blob
3111 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003112 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003113 rounds);
3114 byte[] IV = hexToByteArray(userIvHex);
3115 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3116 c.init(Cipher.DECRYPT_MODE,
3117 new SecretKeySpec(userKey.getEncoded(), "AES"),
3118 ivSpec);
3119 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3120 byte[] mkBlob = c.doFinal(mkCipher);
3121
3122 // first, the master key IV
3123 int offset = 0;
3124 int len = mkBlob[offset++];
3125 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3126 offset += len;
3127 // then the master key itself
3128 len = mkBlob[offset++];
3129 byte[] mk = Arrays.copyOfRange(mkBlob,
3130 offset, offset + len);
3131 offset += len;
3132 // and finally the master key checksum hash
3133 len = mkBlob[offset++];
3134 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3135 offset, offset + len);
3136
3137 // now validate the decrypted master key against the checksum
3138 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3139 if (Arrays.equals(calculatedCk, mkChecksum)) {
3140 ivSpec = new IvParameterSpec(IV);
3141 c.init(Cipher.DECRYPT_MODE,
3142 new SecretKeySpec(mk, "AES"),
3143 ivSpec);
3144 // Only if all of the above worked properly will 'result' be assigned
3145 result = new CipherInputStream(rawInStream, c);
3146 } else Slog.w(TAG, "Incorrect password");
3147 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3148 } catch (InvalidAlgorithmParameterException e) {
3149 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3150 } catch (BadPaddingException e) {
3151 // This case frequently occurs when the wrong password is used to decrypt
3152 // the master key. Use the identical "incorrect password" log text as is
3153 // used in the checksum failure log in order to avoid providing additional
3154 // information to an attacker.
3155 Slog.w(TAG, "Incorrect password");
3156 } catch (IllegalBlockSizeException e) {
3157 Slog.w(TAG, "Invalid block size in master key");
3158 } catch (NoSuchAlgorithmException e) {
3159 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3160 } catch (NoSuchPaddingException e) {
3161 Slog.e(TAG, "Needed padding mechanism unavailable!");
3162 } catch (InvalidKeyException e) {
3163 Slog.w(TAG, "Illegal password; aborting");
3164 } catch (NumberFormatException e) {
3165 Slog.w(TAG, "Can't parse restore data header");
3166 } catch (IOException e) {
3167 Slog.w(TAG, "Can't read input header");
3168 }
3169
3170 return result;
3171 }
3172
Christopher Tate75a99702011-05-18 16:28:19 -07003173 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3174 FileMetadata info;
3175 try {
3176 info = readTarHeaders(instream);
3177 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003178 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003179 dumpFileMetadata(info);
3180 }
3181
3182 final String pkg = info.packageName;
3183 if (!pkg.equals(mAgentPackage)) {
3184 // okay, change in package; set up our various
3185 // bookkeeping if we haven't seen it yet
3186 if (!mPackagePolicies.containsKey(pkg)) {
3187 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3188 }
3189
3190 // Clean up the previous agent relationship if necessary,
3191 // and let the observer know we're considering a new app.
3192 if (mAgent != null) {
3193 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3194 tearDownPipes();
3195 tearDownAgent(mTargetApp);
3196 mTargetApp = null;
3197 mAgentPackage = null;
3198 }
3199 }
3200
3201 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3202 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3203 mPackageInstallers.put(pkg, info.installerPackageName);
3204 // We've read only the manifest content itself at this point,
3205 // so consume the footer before looping around to the next
3206 // input file
3207 skipTarPadding(info.size, instream);
3208 sendOnRestorePackage(pkg);
3209 } else {
3210 // Non-manifest, so it's actual file data. Is this a package
3211 // we're ignoring?
3212 boolean okay = true;
3213 RestorePolicy policy = mPackagePolicies.get(pkg);
3214 switch (policy) {
3215 case IGNORE:
3216 okay = false;
3217 break;
3218
3219 case ACCEPT_IF_APK:
3220 // If we're in accept-if-apk state, then the first file we
3221 // see MUST be the apk.
3222 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3223 if (DEBUG) Slog.d(TAG, "APK file; installing");
3224 // Try to install the app.
3225 String installerName = mPackageInstallers.get(pkg);
3226 okay = installApk(info, installerName, instream);
3227 // good to go; promote to ACCEPT
3228 mPackagePolicies.put(pkg, (okay)
3229 ? RestorePolicy.ACCEPT
3230 : RestorePolicy.IGNORE);
3231 // At this point we've consumed this file entry
3232 // ourselves, so just strip the tar footer and
3233 // go on to the next file in the input stream
3234 skipTarPadding(info.size, instream);
3235 return true;
3236 } else {
3237 // File data before (or without) the apk. We can't
3238 // handle it coherently in this case so ignore it.
3239 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3240 okay = false;
3241 }
3242 break;
3243
3244 case ACCEPT:
3245 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3246 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3247 // we can take the data without the apk, so we
3248 // *want* to do so. skip the apk by declaring this
3249 // one file not-okay without changing the restore
3250 // policy for the package.
3251 okay = false;
3252 }
3253 break;
3254
3255 default:
3256 // Something has gone dreadfully wrong when determining
3257 // the restore policy from the manifest. Ignore the
3258 // rest of this package's data.
3259 Slog.e(TAG, "Invalid policy from manifest");
3260 okay = false;
3261 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3262 break;
3263 }
3264
3265 // If the policy is satisfied, go ahead and set up to pipe the
3266 // data to the agent.
3267 if (DEBUG && okay && mAgent != null) {
3268 Slog.i(TAG, "Reusing existing agent instance");
3269 }
3270 if (okay && mAgent == null) {
3271 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3272
3273 try {
3274 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3275
3276 // If we haven't sent any data to this app yet, we probably
3277 // need to clear it first. Check that.
3278 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003279 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003280 // responsible for coherently managing a full
3281 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003282 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003283 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3284 clearApplicationDataSynchronous(pkg);
3285 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003286 if (DEBUG) Slog.d(TAG, "backup agent ("
3287 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003288 }
3289 mClearedPackages.add(pkg);
3290 } else {
3291 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3292 }
3293
3294 // All set; now set up the IPC and launch the agent
3295 setUpPipes();
3296 mAgent = bindToAgentSynchronous(mTargetApp,
3297 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3298 mAgentPackage = pkg;
3299 } catch (IOException e) {
3300 // fall through to error handling
3301 } catch (NameNotFoundException e) {
3302 // fall through to error handling
3303 }
3304
3305 if (mAgent == null) {
3306 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3307 okay = false;
3308 tearDownPipes();
3309 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3310 }
3311 }
3312
3313 // Sanity check: make sure we never give data to the wrong app. This
3314 // should never happen but a little paranoia here won't go amiss.
3315 if (okay && !pkg.equals(mAgentPackage)) {
3316 Slog.e(TAG, "Restoring data for " + pkg
3317 + " but agent is for " + mAgentPackage);
3318 okay = false;
3319 }
3320
3321 // At this point we have an agent ready to handle the full
3322 // restore data as well as a pipe for sending data to
3323 // that agent. Tell the agent to start reading from the
3324 // pipe.
3325 if (okay) {
3326 boolean agentSuccess = true;
3327 long toCopy = info.size;
3328 final int token = generateToken();
3329 try {
3330 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3331 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003332 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003333 // fire up the app's agent listening on the socket. If
3334 // the agent is running in the system process we can't
3335 // just invoke it asynchronously, so we provide a thread
3336 // for it here.
3337 if (mTargetApp.processName.equals("system")) {
3338 Slog.d(TAG, "system process agent - spinning a thread");
3339 RestoreFileRunnable runner = new RestoreFileRunnable(
3340 mAgent, info, mPipes[0], token);
3341 new Thread(runner).start();
3342 } else {
3343 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3344 info.domain, info.path, info.mode, info.mtime,
3345 token, mBackupManagerBinder);
3346 }
3347 } catch (IOException e) {
3348 // couldn't dup the socket for a process-local restore
3349 Slog.d(TAG, "Couldn't establish restore");
3350 agentSuccess = false;
3351 okay = false;
3352 } catch (RemoteException e) {
3353 // whoops, remote agent went away. We'll eat the content
3354 // ourselves, then, and not copy it over.
3355 Slog.e(TAG, "Agent crashed during full restore");
3356 agentSuccess = false;
3357 okay = false;
3358 }
3359
3360 // Copy over the data if the agent is still good
3361 if (okay) {
3362 boolean pipeOkay = true;
3363 FileOutputStream pipe = new FileOutputStream(
3364 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003365 while (toCopy > 0) {
3366 int toRead = (toCopy > buffer.length)
3367 ? buffer.length : (int)toCopy;
3368 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003369 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003370 if (nRead <= 0) break;
3371 toCopy -= nRead;
3372
3373 // send it to the output pipe as long as things
3374 // are still good
3375 if (pipeOkay) {
3376 try {
3377 pipe.write(buffer, 0, nRead);
3378 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003379 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003380 pipeOkay = false;
3381 }
3382 }
3383 }
3384
3385 // done sending that file! Now we just need to consume
3386 // the delta from info.size to the end of block.
3387 skipTarPadding(info.size, instream);
3388
3389 // and now that we've sent it all, wait for the remote
3390 // side to acknowledge receipt
3391 agentSuccess = waitUntilOperationComplete(token);
3392 }
3393
3394 // okay, if the remote end failed at any point, deal with
3395 // it by ignoring the rest of the restore on it
3396 if (!agentSuccess) {
3397 mBackupHandler.removeMessages(MSG_TIMEOUT);
3398 tearDownPipes();
3399 tearDownAgent(mTargetApp);
3400 mAgent = null;
3401 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3402 }
3403 }
3404
3405 // Problems setting up the agent communication, or an already-
3406 // ignored package: skip to the next tar stream entry by
3407 // reading and discarding this file.
3408 if (!okay) {
3409 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3410 long bytesToConsume = (info.size + 511) & ~511;
3411 while (bytesToConsume > 0) {
3412 int toRead = (bytesToConsume > buffer.length)
3413 ? buffer.length : (int)bytesToConsume;
3414 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003415 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003416 if (nRead <= 0) break;
3417 bytesToConsume -= nRead;
3418 }
3419 }
3420 }
3421 }
3422 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003423 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003424 // treat as EOF
3425 info = null;
3426 }
3427
3428 return (info != null);
3429 }
3430
3431 void setUpPipes() throws IOException {
3432 mPipes = ParcelFileDescriptor.createPipe();
3433 }
3434
3435 void tearDownPipes() {
3436 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003437 try {
3438 mPipes[0].close();
3439 mPipes[0] = null;
3440 mPipes[1].close();
3441 mPipes[1] = null;
3442 } catch (IOException e) {
3443 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003444 }
3445 mPipes = null;
3446 }
3447 }
3448
3449 void tearDownAgent(ApplicationInfo app) {
3450 if (mAgent != null) {
3451 try {
3452 // unbind and tidy up even on timeout or failure, just in case
3453 mActivityManager.unbindBackupAgent(app);
3454
3455 // The agent was running with a stub Application object, so shut it down.
3456 // !!! We hardcode the confirmation UI's package name here rather than use a
3457 // manifest flag! TODO something less direct.
3458 if (app.uid != Process.SYSTEM_UID
3459 && !app.packageName.equals("com.android.backupconfirm")) {
3460 if (DEBUG) Slog.d(TAG, "Killing host process");
3461 mActivityManager.killApplicationProcess(app.processName, app.uid);
3462 } else {
3463 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3464 }
3465 } catch (RemoteException e) {
3466 Slog.d(TAG, "Lost app trying to shut down");
3467 }
3468 mAgent = null;
3469 }
3470 }
3471
3472 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3473 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003474 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003475 int mResult;
3476
3477 public void reset() {
3478 synchronized (mDone) {
3479 mDone.set(false);
3480 }
3481 }
3482
3483 public void waitForCompletion() {
3484 synchronized (mDone) {
3485 while (mDone.get() == false) {
3486 try {
3487 mDone.wait();
3488 } catch (InterruptedException e) { }
3489 }
3490 }
3491 }
3492
3493 int getResult() {
3494 return mResult;
3495 }
3496
3497 @Override
3498 public void packageInstalled(String packageName, int returnCode)
3499 throws RemoteException {
3500 synchronized (mDone) {
3501 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003502 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003503 mDone.set(true);
3504 mDone.notifyAll();
3505 }
3506 }
3507 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003508
3509 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3510 final AtomicBoolean mDone = new AtomicBoolean();
3511 int mResult;
3512
3513 public void reset() {
3514 synchronized (mDone) {
3515 mDone.set(false);
3516 }
3517 }
3518
3519 public void waitForCompletion() {
3520 synchronized (mDone) {
3521 while (mDone.get() == false) {
3522 try {
3523 mDone.wait();
3524 } catch (InterruptedException e) { }
3525 }
3526 }
3527 }
3528
3529 @Override
3530 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3531 synchronized (mDone) {
3532 mResult = returnCode;
3533 mDone.set(true);
3534 mDone.notifyAll();
3535 }
3536 }
3537 }
3538
Christopher Tate75a99702011-05-18 16:28:19 -07003539 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003540 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003541
3542 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3543 boolean okay = true;
3544
3545 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3546
3547 // The file content is an .apk file. Copy it out to a staging location and
3548 // attempt to install it.
3549 File apkFile = new File(mDataDir, info.packageName);
3550 try {
3551 FileOutputStream apkStream = new FileOutputStream(apkFile);
3552 byte[] buffer = new byte[32 * 1024];
3553 long size = info.size;
3554 while (size > 0) {
3555 long toRead = (buffer.length < size) ? buffer.length : size;
3556 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003557 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003558 apkStream.write(buffer, 0, didRead);
3559 size -= didRead;
3560 }
3561 apkStream.close();
3562
3563 // make sure the installer can read it
3564 apkFile.setReadable(true, false);
3565
3566 // Now install it
3567 Uri packageUri = Uri.fromFile(apkFile);
3568 mInstallObserver.reset();
3569 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003570 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3571 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003572 mInstallObserver.waitForCompletion();
3573
3574 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3575 // The only time we continue to accept install of data even if the
3576 // apk install failed is if we had already determined that we could
3577 // accept the data regardless.
3578 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3579 okay = false;
3580 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003581 } else {
3582 // Okay, the install succeeded. Make sure it was the right app.
3583 boolean uninstall = false;
3584 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3585 Slog.w(TAG, "Restore stream claimed to include apk for "
3586 + info.packageName + " but apk was really "
3587 + mInstallObserver.mPackageName);
3588 // delete the package we just put in place; it might be fraudulent
3589 okay = false;
3590 uninstall = true;
3591 } else {
3592 try {
3593 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3594 PackageManager.GET_SIGNATURES);
3595 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3596 Slog.w(TAG, "Restore stream contains apk of package "
3597 + info.packageName + " but it disallows backup/restore");
3598 okay = false;
3599 } else {
3600 // So far so good -- do the signatures match the manifest?
3601 Signature[] sigs = mManifestSignatures.get(info.packageName);
3602 if (!signaturesMatch(sigs, pkg)) {
3603 Slog.w(TAG, "Installed app " + info.packageName
3604 + " signatures do not match restore manifest");
3605 okay = false;
3606 uninstall = true;
3607 }
3608 }
3609 } catch (NameNotFoundException e) {
3610 Slog.w(TAG, "Install of package " + info.packageName
3611 + " succeeded but now not found");
3612 okay = false;
3613 }
3614 }
3615
3616 // If we're not okay at this point, we need to delete the package
3617 // that we just installed.
3618 if (uninstall) {
3619 mDeleteObserver.reset();
3620 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3621 mDeleteObserver, 0);
3622 mDeleteObserver.waitForCompletion();
3623 }
Christopher Tate75a99702011-05-18 16:28:19 -07003624 }
3625 } catch (IOException e) {
3626 Slog.e(TAG, "Unable to transcribe restored apk for install");
3627 okay = false;
3628 } finally {
3629 apkFile.delete();
3630 }
3631
3632 return okay;
3633 }
3634
3635 // Given an actual file content size, consume the post-content padding mandated
3636 // by the tar format.
3637 void skipTarPadding(long size, InputStream instream) throws IOException {
3638 long partial = (size + 512) % 512;
3639 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003640 final int needed = 512 - (int)partial;
3641 byte[] buffer = new byte[needed];
3642 if (readExactly(instream, buffer, 0, needed) == needed) {
3643 mBytes += needed;
3644 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003645 }
3646 }
3647
3648 // Returns a policy constant; takes a buffer arg to reduce memory churn
3649 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3650 throws IOException {
3651 // Fail on suspiciously large manifest files
3652 if (info.size > 64 * 1024) {
3653 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3654 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003655
Christopher Tate75a99702011-05-18 16:28:19 -07003656 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003657 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3658 mBytes += info.size;
3659 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003660
3661 RestorePolicy policy = RestorePolicy.IGNORE;
3662 String[] str = new String[1];
3663 int offset = 0;
3664
3665 try {
3666 offset = extractLine(buffer, offset, str);
3667 int version = Integer.parseInt(str[0]);
3668 if (version == BACKUP_MANIFEST_VERSION) {
3669 offset = extractLine(buffer, offset, str);
3670 String manifestPackage = str[0];
3671 // TODO: handle <original-package>
3672 if (manifestPackage.equals(info.packageName)) {
3673 offset = extractLine(buffer, offset, str);
3674 version = Integer.parseInt(str[0]); // app version
3675 offset = extractLine(buffer, offset, str);
3676 int platformVersion = Integer.parseInt(str[0]);
3677 offset = extractLine(buffer, offset, str);
3678 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3679 offset = extractLine(buffer, offset, str);
3680 boolean hasApk = str[0].equals("1");
3681 offset = extractLine(buffer, offset, str);
3682 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003683 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003684 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003685 for (int i = 0; i < numSigs; i++) {
3686 offset = extractLine(buffer, offset, str);
3687 sigs[i] = new Signature(str[0]);
3688 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003689 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003690
3691 // Okay, got the manifest info we need...
3692 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003693 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3694 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003695 // Fall through to IGNORE if the app explicitly disallows backup
3696 final int flags = pkgInfo.applicationInfo.flags;
3697 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003698 // Restore system-uid-space packages only if they have
3699 // defined a custom backup agent
3700 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
3701 || (pkgInfo.applicationInfo.backupAgentName != null)) {
3702 // Verify signatures against any installed version; if they
3703 // don't match, then we fall though and ignore the data. The
3704 // signatureMatch() method explicitly ignores the signature
3705 // check for packages installed on the system partition, because
3706 // such packages are signed with the platform cert instead of
3707 // the app developer's cert, so they're different on every
3708 // device.
3709 if (signaturesMatch(sigs, pkgInfo)) {
3710 if (pkgInfo.versionCode >= version) {
3711 Slog.i(TAG, "Sig + version match; taking data");
3712 policy = RestorePolicy.ACCEPT;
3713 } else {
3714 // The data is from a newer version of the app than
3715 // is presently installed. That means we can only
3716 // use it if the matching apk is also supplied.
3717 Slog.d(TAG, "Data version " + version
3718 + " is newer than installed version "
3719 + pkgInfo.versionCode + " - requiring apk");
3720 policy = RestorePolicy.ACCEPT_IF_APK;
3721 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003722 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003723 Slog.w(TAG, "Restore manifest signatures do not match "
3724 + "installed application for " + info.packageName);
Christopher Tatea858cb02011-06-03 12:27:51 -07003725 }
Christopher Tate75a99702011-05-18 16:28:19 -07003726 } else {
Christopher Tatef6d6fa82012-09-26 15:25:59 -07003727 Slog.w(TAG, "Package " + info.packageName
3728 + " is system level with no agent");
Christopher Tate75a99702011-05-18 16:28:19 -07003729 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003730 } else {
3731 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3732 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003733 }
3734 } catch (NameNotFoundException e) {
3735 // Okay, the target app isn't installed. We can process
3736 // the restore properly only if the dataset provides the
3737 // apk file and we can successfully install it.
3738 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3739 + " not installed; requiring apk in dataset");
3740 policy = RestorePolicy.ACCEPT_IF_APK;
3741 }
3742
3743 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3744 Slog.i(TAG, "Cannot restore package " + info.packageName
3745 + " without the matching .apk");
3746 }
3747 } else {
3748 Slog.i(TAG, "Missing signature on backed-up package "
3749 + info.packageName);
3750 }
3751 } else {
3752 Slog.i(TAG, "Expected package " + info.packageName
3753 + " but restore manifest claims " + manifestPackage);
3754 }
3755 } else {
3756 Slog.i(TAG, "Unknown restore manifest version " + version
3757 + " for package " + info.packageName);
3758 }
3759 } catch (NumberFormatException e) {
3760 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003761 } catch (IllegalArgumentException e) {
3762 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003763 }
3764
3765 return policy;
3766 }
3767
3768 // Builds a line from a byte buffer starting at 'offset', and returns
3769 // the index of the next unconsumed data in the buffer.
3770 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3771 final int end = buffer.length;
3772 if (offset >= end) throw new IOException("Incomplete data");
3773
3774 int pos;
3775 for (pos = offset; pos < end; pos++) {
3776 byte c = buffer[pos];
3777 // at LF we declare end of line, and return the next char as the
3778 // starting point for the next time through
3779 if (c == '\n') {
3780 break;
3781 }
3782 }
3783 outStr[0] = new String(buffer, offset, pos - offset);
3784 pos++; // may be pointing an extra byte past the end but that's okay
3785 return pos;
3786 }
3787
3788 void dumpFileMetadata(FileMetadata info) {
3789 if (DEBUG) {
3790 StringBuilder b = new StringBuilder(128);
3791
3792 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003793 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003794 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3795 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3796 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3797 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3798 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3799 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3800 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3801 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3802 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3803 b.append(String.format(" %9d ", info.size));
3804
3805 Date stamp = new Date(info.mtime);
3806 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3807
3808 b.append(info.packageName);
3809 b.append(" :: ");
3810 b.append(info.domain);
3811 b.append(" :: ");
3812 b.append(info.path);
3813
3814 Slog.i(TAG, b.toString());
3815 }
3816 }
3817 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3818 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3819 byte[] block = new byte[512];
3820 FileMetadata info = null;
3821
3822 boolean gotHeader = readTarHeader(instream, block);
3823 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003824 try {
3825 // okay, presume we're okay, and extract the various metadata
3826 info = new FileMetadata();
3827 info.size = extractRadix(block, 124, 12, 8);
3828 info.mtime = extractRadix(block, 136, 12, 8);
3829 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003830
Christopher Tate2efd2db2011-07-19 16:32:49 -07003831 info.path = extractString(block, 345, 155); // prefix
3832 String path = extractString(block, 0, 100);
3833 if (path.length() > 0) {
3834 if (info.path.length() > 0) info.path += '/';
3835 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003836 }
Christopher Tate75a99702011-05-18 16:28:19 -07003837
Christopher Tate2efd2db2011-07-19 16:32:49 -07003838 // tar link indicator field: 1 byte at offset 156 in the header.
3839 int typeChar = block[156];
3840 if (typeChar == 'x') {
3841 // pax extended header, so we need to read that
3842 gotHeader = readPaxExtendedHeader(instream, info);
3843 if (gotHeader) {
3844 // and after a pax extended header comes another real header -- read
3845 // that to find the real file type
3846 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003847 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003848 if (!gotHeader) throw new IOException("Bad or missing pax header");
3849
3850 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003851 }
Christopher Tate75a99702011-05-18 16:28:19 -07003852
Christopher Tate2efd2db2011-07-19 16:32:49 -07003853 switch (typeChar) {
3854 case '0': info.type = BackupAgent.TYPE_FILE; break;
3855 case '5': {
3856 info.type = BackupAgent.TYPE_DIRECTORY;
3857 if (info.size != 0) {
3858 Slog.w(TAG, "Directory entry with nonzero size in header");
3859 info.size = 0;
3860 }
3861 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003862 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003863 case 0: {
3864 // presume EOF
3865 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3866 return null;
3867 }
3868 default: {
3869 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3870 throw new IOException("Unknown entity type " + typeChar);
3871 }
Christopher Tate75a99702011-05-18 16:28:19 -07003872 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003873
3874 // Parse out the path
3875 //
3876 // first: apps/shared/unrecognized
3877 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3878 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3879 // File in shared storage. !!! TODO: implement this.
3880 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003881 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003882 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3883 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3884 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3885 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3886 // App content! Parse out the package name and domain
3887
3888 // strip the apps/ prefix
3889 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3890
3891 // extract the package name
3892 int slash = info.path.indexOf('/');
3893 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3894 info.packageName = info.path.substring(0, slash);
3895 info.path = info.path.substring(slash+1);
3896
3897 // if it's a manifest we're done, otherwise parse out the domains
3898 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3899 slash = info.path.indexOf('/');
3900 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3901 info.domain = info.path.substring(0, slash);
3902 // validate that it's one of the domains we understand
3903 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3904 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3905 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3906 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3907 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3908 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3909 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3910 throw new IOException("Unrecognized domain " + info.domain);
3911 }
3912
3913 info.path = info.path.substring(slash + 1);
3914 }
3915 }
3916 } catch (IOException e) {
3917 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003918 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003919 HEXLOG(block);
3920 }
3921 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003922 }
3923 }
3924 return info;
3925 }
3926
Christopher Tate2efd2db2011-07-19 16:32:49 -07003927 private void HEXLOG(byte[] block) {
3928 int offset = 0;
3929 int todo = block.length;
3930 StringBuilder buf = new StringBuilder(64);
3931 while (todo > 0) {
3932 buf.append(String.format("%04x ", offset));
3933 int numThisLine = (todo > 16) ? 16 : todo;
3934 for (int i = 0; i < numThisLine; i++) {
3935 buf.append(String.format("%02x ", block[offset+i]));
3936 }
3937 Slog.i("hexdump", buf.toString());
3938 buf.setLength(0);
3939 todo -= numThisLine;
3940 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003941 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003942 }
3943
Christopher Tate6853fcf2011-08-10 17:52:21 -07003944 // Read exactly the given number of bytes into a buffer at the stated offset.
3945 // Returns false if EOF is encountered before the requested number of bytes
3946 // could be read.
3947 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3948 throws IOException {
3949 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3950
3951 int soFar = 0;
3952 while (soFar < size) {
3953 int nRead = in.read(buffer, offset + soFar, size - soFar);
3954 if (nRead <= 0) {
3955 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3956 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003957 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003958 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003959 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003960 return soFar;
3961 }
3962
3963 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3964 final int got = readExactly(instream, block, 0, 512);
3965 if (got == 0) return false; // Clean EOF
3966 if (got < 512) throw new IOException("Unable to read full block header");
3967 mBytes += 512;
3968 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003969 }
3970
3971 // overwrites 'info' fields based on the pax extended header
3972 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3973 throws IOException {
3974 // We should never see a pax extended header larger than this
3975 if (info.size > 32*1024) {
3976 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3977 + " - aborting");
3978 throw new IOException("Sanity failure: pax header size " + info.size);
3979 }
3980
3981 // read whole blocks, not just the content size
3982 int numBlocks = (int)((info.size + 511) >> 9);
3983 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003984 if (readExactly(instream, data, 0, data.length) < data.length) {
3985 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003986 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003987 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003988
3989 final int contentSize = (int) info.size;
3990 int offset = 0;
3991 do {
3992 // extract the line at 'offset'
3993 int eol = offset+1;
3994 while (eol < contentSize && data[eol] != ' ') eol++;
3995 if (eol >= contentSize) {
3996 // error: we just hit EOD looking for the end of the size field
3997 throw new IOException("Invalid pax data");
3998 }
3999 // eol points to the space between the count and the key
4000 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4001 int key = eol + 1; // start of key=value
4002 eol = offset + linelen - 1; // trailing LF
4003 int value;
4004 for (value = key+1; data[value] != '=' && value <= eol; value++);
4005 if (value > eol) {
4006 throw new IOException("Invalid pax declaration");
4007 }
4008
4009 // pax requires that key/value strings be in UTF-8
4010 String keyStr = new String(data, key, value-key, "UTF-8");
4011 // -1 to strip the trailing LF
4012 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4013
4014 if ("path".equals(keyStr)) {
4015 info.path = valStr;
4016 } else if ("size".equals(keyStr)) {
4017 info.size = Long.parseLong(valStr);
4018 } else {
4019 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4020 }
4021
4022 offset += linelen;
4023 } while (offset < contentSize);
4024
4025 return true;
4026 }
4027
4028 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4029 throws IOException {
4030 long value = 0;
4031 final int end = offset + maxChars;
4032 for (int i = offset; i < end; i++) {
4033 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004034 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004035 if (b == 0 || b == ' ') break;
4036 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004037 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004038 }
4039 value = radix * value + (b - '0');
4040 }
4041 return value;
4042 }
4043
4044 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4045 final int end = offset + maxChars;
4046 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004047 // tar string fields terminate early with a NUL
4048 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004049 return new String(data, offset, eos-offset, "US-ASCII");
4050 }
4051
4052 void sendStartRestore() {
4053 if (mObserver != null) {
4054 try {
4055 mObserver.onStartRestore();
4056 } catch (RemoteException e) {
4057 Slog.w(TAG, "full restore observer went away: startRestore");
4058 mObserver = null;
4059 }
4060 }
4061 }
4062
4063 void sendOnRestorePackage(String name) {
4064 if (mObserver != null) {
4065 try {
4066 // TODO: use a more user-friendly name string
4067 mObserver.onRestorePackage(name);
4068 } catch (RemoteException e) {
4069 Slog.w(TAG, "full restore observer went away: restorePackage");
4070 mObserver = null;
4071 }
4072 }
4073 }
4074
4075 void sendEndRestore() {
4076 if (mObserver != null) {
4077 try {
4078 mObserver.onEndRestore();
4079 } catch (RemoteException e) {
4080 Slog.w(TAG, "full restore observer went away: endRestore");
4081 mObserver = null;
4082 }
4083 }
4084 }
4085 }
4086
Christopher Tatedf01dea2009-06-09 20:45:02 -07004087 // ----- Restore handling -----
4088
Christopher Tate78dd4a72009-11-04 11:49:08 -08004089 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4090 // If the target resides on the system partition, we allow it to restore
4091 // data from the like-named package in a restore set even if the signatures
4092 // do not match. (Unlike general applications, those flashed to the system
4093 // partition will be signed with the device's platform certificate, so on
4094 // different phones the same system app will have different signatures.)
4095 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004096 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004097 return true;
4098 }
4099
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004100 // Allow unsigned apps, but not signed on one device and unsigned on the other
4101 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004102 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004103 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004104 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004105 if ((storedSigs == null || storedSigs.length == 0)
4106 && (deviceSigs == null || deviceSigs.length == 0)) {
4107 return true;
4108 }
4109 if (storedSigs == null || deviceSigs == null) {
4110 return false;
4111 }
4112
Christopher Tateabce4e82009-06-18 18:35:32 -07004113 // !!! TODO: this demands that every stored signature match one
4114 // that is present on device, and does not demand the converse.
4115 // Is this this right policy?
4116 int nStored = storedSigs.length;
4117 int nDevice = deviceSigs.length;
4118
4119 for (int i=0; i < nStored; i++) {
4120 boolean match = false;
4121 for (int j=0; j < nDevice; j++) {
4122 if (storedSigs[i].equals(deviceSigs[j])) {
4123 match = true;
4124 break;
4125 }
4126 }
4127 if (!match) {
4128 return false;
4129 }
4130 }
4131 return true;
4132 }
4133
Christopher Tate2982d062011-09-06 20:35:24 -07004134 enum RestoreState {
4135 INITIAL,
4136 DOWNLOAD_DATA,
4137 PM_METADATA,
4138 RUNNING_QUEUE,
4139 FINAL
4140 }
4141
4142 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004143 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004144 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004145 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004146 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004147 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004148 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004149 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004150 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004151 private long mStartRealtime;
4152 private PackageManagerBackupAgent mPmAgent;
4153 private List<PackageInfo> mAgentPackages;
4154 private ArrayList<PackageInfo> mRestorePackages;
4155 private RestoreState mCurrentState;
4156 private int mCount;
4157 private boolean mFinished;
4158 private int mStatus;
4159 private File mBackupDataName;
4160 private File mNewStateName;
4161 private File mSavedStateName;
4162 private ParcelFileDescriptor mBackupData;
4163 private ParcelFileDescriptor mNewState;
4164 private PackageInfo mCurrentPackage;
4165
Christopher Tatedf01dea2009-06-09 20:45:02 -07004166
Christopher Tate5cbbf562009-06-22 16:44:51 -07004167 class RestoreRequest {
4168 public PackageInfo app;
4169 public int storedAppVersion;
4170
4171 RestoreRequest(PackageInfo _app, int _version) {
4172 app = _app;
4173 storedAppVersion = _version;
4174 }
4175 }
4176
Christopher Tate44a27902010-01-27 17:15:49 -08004177 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004178 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004179 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004180 mCurrentState = RestoreState.INITIAL;
4181 mFinished = false;
4182 mPmAgent = null;
4183
Christopher Tatedf01dea2009-06-09 20:45:02 -07004184 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004185 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004186 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004187 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004188 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004189 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004190
Christopher Tate284f1bb2011-07-07 14:31:18 -07004191 if (filterSet != null) {
4192 mFilterSet = new HashSet<String>();
4193 for (String pkg : filterSet) {
4194 mFilterSet.add(pkg);
4195 }
4196 } else {
4197 mFilterSet = null;
4198 }
4199
Christopher Tate5cb400b2009-06-25 16:03:14 -07004200 try {
4201 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4202 } catch (RemoteException e) {
4203 // can't happen; the transport is local
4204 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004205 }
4206
Christopher Tate2982d062011-09-06 20:35:24 -07004207 // Execute one tick of whatever state machine the task implements
4208 @Override
4209 public void execute() {
4210 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4211 switch (mCurrentState) {
4212 case INITIAL:
4213 beginRestore();
4214 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004215
Christopher Tate2982d062011-09-06 20:35:24 -07004216 case DOWNLOAD_DATA:
4217 downloadRestoreData();
4218 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004219
Christopher Tate2982d062011-09-06 20:35:24 -07004220 case PM_METADATA:
4221 restorePmMetadata();
4222 break;
4223
4224 case RUNNING_QUEUE:
4225 restoreNextAgent();
4226 break;
4227
4228 case FINAL:
4229 if (!mFinished) finalizeRestore();
4230 else {
4231 Slog.e(TAG, "Duplicate finish");
4232 }
4233 mFinished = true;
4234 break;
4235 }
4236 }
4237
4238 // Initialize and set up for the PM metadata restore, which comes first
4239 void beginRestore() {
4240 // Don't account time doing the restore as inactivity of the app
4241 // that has opened a restore session.
4242 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4243
4244 // Assume error until we successfully init everything
4245 mStatus = BackupConstants.TRANSPORT_ERROR;
4246
Christopher Tatedf01dea2009-06-09 20:45:02 -07004247 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004248 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004249 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004250
Dan Egnorefe52642009-06-24 00:16:33 -07004251 // Get the list of all packages which have backup enabled.
4252 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004253 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004254 PackageInfo omPackage = new PackageInfo();
4255 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004256 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004257
Christopher Tate2982d062011-09-06 20:35:24 -07004258 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004259 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004260 // if there's a filter set, strip out anything that isn't
4261 // present before proceeding
4262 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004263 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4264 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004265 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004266 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004267 }
4268 }
Christopher Tate2982d062011-09-06 20:35:24 -07004269 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004270 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004271 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004272 Slog.i(TAG, " " + p);
4273 }
4274 }
4275 }
Christopher Tate2982d062011-09-06 20:35:24 -07004276 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004277 } else {
4278 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004279 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004280 }
Dan Egnorefe52642009-06-24 00:16:33 -07004281
Christopher Tate7d562ec2009-06-25 18:03:43 -07004282 // let the observer know that we're running
4283 if (mObserver != null) {
4284 try {
4285 // !!! TODO: get an actual count from the transport after
4286 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004287 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004288 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004289 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004290 mObserver = null;
4291 }
4292 }
Christopher Tate2982d062011-09-06 20:35:24 -07004293 } catch (RemoteException e) {
4294 // Something has gone catastrophically wrong with the transport
4295 Slog.e(TAG, "Error communicating with transport for restore");
4296 executeNextState(RestoreState.FINAL);
4297 return;
4298 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004299
Christopher Tate2982d062011-09-06 20:35:24 -07004300 mStatus = BackupConstants.TRANSPORT_OK;
4301 executeNextState(RestoreState.DOWNLOAD_DATA);
4302 }
4303
4304 void downloadRestoreData() {
4305 // Note that the download phase can be very time consuming, but we're executing
4306 // it inline here on the looper. This is "okay" because it is not calling out to
4307 // third party code; the transport is "trusted," and so we assume it is being a
4308 // good citizen and timing out etc when appropriate.
4309 //
4310 // TODO: when appropriate, move the download off the looper and rearrange the
4311 // error handling around that.
4312 try {
4313 mStatus = mTransport.startRestore(mToken,
4314 mRestorePackages.toArray(new PackageInfo[0]));
4315 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004317 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004318 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004319 return;
4320 }
Christopher Tate2982d062011-09-06 20:35:24 -07004321 } catch (RemoteException e) {
4322 Slog.e(TAG, "Error communicating with transport for restore");
4323 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4324 mStatus = BackupConstants.TRANSPORT_ERROR;
4325 executeNextState(RestoreState.FINAL);
4326 return;
4327 }
Dan Egnorefe52642009-06-24 00:16:33 -07004328
Christopher Tate2982d062011-09-06 20:35:24 -07004329 // Successful download of the data to be parceled out to the apps, so off we go.
4330 executeNextState(RestoreState.PM_METADATA);
4331 }
4332
4333 void restorePmMetadata() {
4334 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004335 String packageName = mTransport.nextRestorePackage();
4336 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004337 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004338 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004339 mStatus = BackupConstants.TRANSPORT_ERROR;
4340 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004341 return;
4342 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004343 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004344 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004345 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004346 mStatus = BackupConstants.TRANSPORT_OK;
4347 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004348 return;
4349 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004350 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004351 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004352 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004353 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004354 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004355 return;
4356 }
4357
4358 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004359 PackageInfo omPackage = new PackageInfo();
4360 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4361 mPmAgent = new PackageManagerBackupAgent(
4362 mPackageManager, mAgentPackages);
4363 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004364 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004365 // The PM agent called operationComplete() already, because our invocation
4366 // of it is process-local and therefore synchronous. That means that a
4367 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4368 // proceed with running the queue do we remove that pending message and
4369 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004370
Christopher Tate8c032472009-07-02 14:28:47 -07004371 // Verify that the backup set includes metadata. If not, we can't do
4372 // signature/version verification etc, so we simply do not proceed with
4373 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004374 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004375 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004376 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004377 "Package manager restore metadata missing");
4378 mStatus = BackupConstants.TRANSPORT_ERROR;
4379 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4380 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004381 return;
4382 }
Christopher Tate2982d062011-09-06 20:35:24 -07004383 } catch (RemoteException e) {
4384 Slog.e(TAG, "Error communicating with transport for restore");
4385 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4386 mStatus = BackupConstants.TRANSPORT_ERROR;
4387 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4388 executeNextState(RestoreState.FINAL);
4389 return;
4390 }
Christopher Tate8c032472009-07-02 14:28:47 -07004391
Christopher Tate2982d062011-09-06 20:35:24 -07004392 // Metadata is intact, so we can now run the restore queue. If we get here,
4393 // we have already enqueued the necessary next-step message on the looper.
4394 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004395
Christopher Tate2982d062011-09-06 20:35:24 -07004396 void restoreNextAgent() {
4397 try {
4398 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004399
Christopher Tate2982d062011-09-06 20:35:24 -07004400 if (packageName == null) {
4401 Slog.e(TAG, "Error getting next restore package");
4402 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4403 executeNextState(RestoreState.FINAL);
4404 return;
4405 } else if (packageName.equals("")) {
4406 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4407 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4408 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4409 executeNextState(RestoreState.FINAL);
4410 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004411 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004412
4413 if (mObserver != null) {
4414 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004415 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004416 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004417 Slog.d(TAG, "Restore observer died in onUpdate");
4418 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004419 }
4420 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004421
Christopher Tate2982d062011-09-06 20:35:24 -07004422 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4423 if (metaInfo == null) {
4424 Slog.e(TAG, "Missing metadata for " + packageName);
4425 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4426 "Package metadata missing");
4427 executeNextState(RestoreState.RUNNING_QUEUE);
4428 return;
Christopher Tate84725812010-02-04 15:52:40 -08004429 }
4430
Christopher Tate2982d062011-09-06 20:35:24 -07004431 PackageInfo packageInfo;
4432 try {
4433 int flags = PackageManager.GET_SIGNATURES;
4434 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4435 } catch (NameNotFoundException e) {
4436 Slog.e(TAG, "Invalid package restoring data", e);
4437 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4438 "Package missing on device");
4439 executeNextState(RestoreState.RUNNING_QUEUE);
4440 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004441 }
4442
Christopher Tatee7287a02012-09-07 18:32:12 -07004443 if (packageInfo.applicationInfo.backupAgentName == null
4444 || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4445 if (DEBUG) {
4446 Slog.i(TAG, "Data exists for package " + packageName
4447 + " but app has no agent; skipping");
4448 }
4449 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4450 "Package has no agent");
4451 executeNextState(RestoreState.RUNNING_QUEUE);
4452 return;
4453 }
4454
Christopher Tate2982d062011-09-06 20:35:24 -07004455 if (metaInfo.versionCode > packageInfo.versionCode) {
4456 // Data is from a "newer" version of the app than we have currently
4457 // installed. If the app has not declared that it is prepared to
4458 // handle this case, we do not attempt the restore.
4459 if ((packageInfo.applicationInfo.flags
4460 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4461 String message = "Version " + metaInfo.versionCode
4462 + " > installed version " + packageInfo.versionCode;
4463 Slog.w(TAG, "Package " + packageName + ": " + message);
4464 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4465 packageName, message);
4466 executeNextState(RestoreState.RUNNING_QUEUE);
4467 return;
4468 } else {
4469 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4470 + " > installed " + packageInfo.versionCode
4471 + " but restoreAnyVersion");
4472 }
4473 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004474
Christopher Tate2982d062011-09-06 20:35:24 -07004475 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4476 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4477 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4478 "Signature mismatch");
4479 executeNextState(RestoreState.RUNNING_QUEUE);
4480 return;
4481 }
4482
4483 if (DEBUG) Slog.v(TAG, "Package " + packageName
4484 + " restore version [" + metaInfo.versionCode
4485 + "] is compatible with installed version ["
4486 + packageInfo.versionCode + "]");
4487
4488 // Then set up and bind the agent
4489 IBackupAgent agent = bindToAgentSynchronous(
4490 packageInfo.applicationInfo,
4491 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4492 if (agent == null) {
4493 Slog.w(TAG, "Can't find backup agent for " + packageName);
4494 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4495 "Restore agent missing");
4496 executeNextState(RestoreState.RUNNING_QUEUE);
4497 return;
4498 }
4499
4500 // And then finally start the restore on this agent
4501 try {
4502 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4503 ++mCount;
4504 } catch (Exception e) {
4505 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4506 agentErrorCleanup();
4507 executeNextState(RestoreState.RUNNING_QUEUE);
4508 }
4509 } catch (RemoteException e) {
4510 Slog.e(TAG, "Unable to fetch restore data from transport");
4511 mStatus = BackupConstants.TRANSPORT_ERROR;
4512 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004513 }
4514 }
4515
Christopher Tate2982d062011-09-06 20:35:24 -07004516 void finalizeRestore() {
4517 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4518
4519 try {
4520 mTransport.finishRestore();
4521 } catch (RemoteException e) {
4522 Slog.e(TAG, "Error finishing restore", e);
4523 }
4524
4525 if (mObserver != null) {
4526 try {
4527 mObserver.restoreFinished(mStatus);
4528 } catch (RemoteException e) {
4529 Slog.d(TAG, "Restore observer died at restoreFinished");
4530 }
4531 }
4532
4533 // If this was a restoreAll operation, record that this was our
4534 // ancestral dataset, as well as the set of apps that are possibly
4535 // restoreable from the dataset
4536 if (mTargetPackage == null && mPmAgent != null) {
4537 mAncestralPackages = mPmAgent.getRestoredPackages();
4538 mAncestralToken = mToken;
4539 writeRestoreTokens();
4540 }
4541
4542 // We must under all circumstances tell the Package Manager to
4543 // proceed with install notifications if it's waiting for us.
4544 if (mPmToken > 0) {
4545 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4546 try {
4547 mPackageManagerBinder.finishPackageInstall(mPmToken);
4548 } catch (RemoteException e) { /* can't happen */ }
4549 }
4550
4551 // Furthermore we need to reset the session timeout clock
4552 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4553 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4554 TIMEOUT_RESTORE_INTERVAL);
4555
4556 // done; we can finally release the wakelock
4557 Slog.i(TAG, "Restore complete.");
4558 mWakelock.release();
4559 }
4560
4561 // Call asynchronously into the app, passing it the restore data. The next step
4562 // after this is always a callback, either operationComplete() or handleTimeout().
4563 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004564 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004565 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004566 final String packageName = app.packageName;
4567
Christopher Tate2982d062011-09-06 20:35:24 -07004568 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004569
Christopher Tatec7b31e32009-06-10 15:49:30 -07004570 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004571 mBackupDataName = new File(mDataDir, packageName + ".restore");
4572 mNewStateName = new File(mStateDir, packageName + ".new");
4573 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004574
Christopher Tate4a627c72011-04-01 14:43:32 -07004575 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004576 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004577 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004578 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004579 ParcelFileDescriptor.MODE_READ_WRITE |
4580 ParcelFileDescriptor.MODE_CREATE |
4581 ParcelFileDescriptor.MODE_TRUNCATE);
4582
rpcraigebab0ae2012-12-04 09:37:23 -05004583 if (!SELinux.restorecon(mBackupDataName)) {
4584 Slog.e(TAG, "SElinux restorecon failed for " + mBackupDataName);
4585 }
4586
Christopher Tate2982d062011-09-06 20:35:24 -07004587 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004588 // Transport-level failure, so we wind everything up and
4589 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004590 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004591 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004592 mBackupData.close();
4593 mBackupDataName.delete();
4594 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004595 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004596 }
4597
4598 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004599 mBackupData.close();
4600 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004601 ParcelFileDescriptor.MODE_READ_ONLY);
4602
Christopher Tate2982d062011-09-06 20:35:24 -07004603 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004604 ParcelFileDescriptor.MODE_READ_WRITE |
4605 ParcelFileDescriptor.MODE_CREATE |
4606 ParcelFileDescriptor.MODE_TRUNCATE);
4607
Christopher Tate44a27902010-01-27 17:15:49 -08004608 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004609 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4610 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004611 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004612 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004613 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004614 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004615
Christopher Tate2982d062011-09-06 20:35:24 -07004616 // After a restore failure we go back to running the queue. If there
4617 // are no more packages to be restored that will be handled by the
4618 // next step.
4619 executeNextState(RestoreState.RUNNING_QUEUE);
4620 }
4621 }
Chris Tate249345b2010-10-29 12:57:04 -07004622
Christopher Tate2982d062011-09-06 20:35:24 -07004623 void agentErrorCleanup() {
4624 // If the agent fails restore, it might have put the app's data
4625 // into an incoherent state. For consistency we wipe its data
4626 // again in this case before continuing with normal teardown
4627 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4628 agentCleanup();
4629 }
4630
4631 void agentCleanup() {
4632 mBackupDataName.delete();
4633 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4634 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4635 mBackupData = mNewState = null;
4636
4637 // if everything went okay, remember the recorded state now
4638 //
4639 // !!! TODO: the restored data should be migrated on the server
4640 // side into the current dataset. In that case the new state file
4641 // we just created would reflect the data already extant in the
4642 // backend, so there'd be nothing more to do. Until that happens,
4643 // however, we need to make sure that we record the data to the
4644 // current backend dataset. (Yes, this means shipping the data over
4645 // the wire in both directions. That's bad, but consistency comes
4646 // first, then efficiency.) Once we introduce server-side data
4647 // migration to the newly-restored device's dataset, we will change
4648 // the following from a discard of the newly-written state to the
4649 // "correct" operation of renaming into the canonical state blob.
4650 mNewStateName.delete(); // TODO: remove; see above comment
4651 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4652
4653 // If this wasn't the PM pseudopackage, tear down the agent side
4654 if (mCurrentPackage.applicationInfo != null) {
4655 // unbind and tidy up even on timeout or failure
4656 try {
4657 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4658
4659 // The agent was probably running with a stub Application object,
4660 // which isn't a valid run mode for the main app logic. Shut
4661 // down the app so that next time it's launched, it gets the
4662 // usual full initialization. Note that this is only done for
4663 // full-system restores: when a single app has requested a restore,
4664 // it is explicitly not killed following that operation.
4665 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4666 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4667 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4668 + mCurrentPackage.applicationInfo.processName);
4669 mActivityManager.killApplicationProcess(
4670 mCurrentPackage.applicationInfo.processName,
4671 mCurrentPackage.applicationInfo.uid);
4672 }
4673 } catch (RemoteException e) {
4674 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004675 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004676 }
Christopher Tate2982d062011-09-06 20:35:24 -07004677
4678 // The caller is responsible for reestablishing the state machine; our
4679 // responsibility here is to clear the decks for whatever comes next.
4680 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4681 synchronized (mCurrentOpLock) {
4682 mCurrentOperations.clear();
4683 }
4684 }
4685
4686 // A call to agent.doRestore() has been positively acknowledged as complete
4687 @Override
4688 public void operationComplete() {
4689 int size = (int) mBackupDataName.length();
4690 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4691 // Just go back to running the restore queue
4692 agentCleanup();
4693
4694 executeNextState(RestoreState.RUNNING_QUEUE);
4695 }
4696
4697 // A call to agent.doRestore() has timed out
4698 @Override
4699 public void handleTimeout() {
4700 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4701 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4702 mCurrentPackage.packageName, "restore timeout");
4703 // Handle like an agent that threw on invocation: wipe it and go on to the next
4704 agentErrorCleanup();
4705 executeNextState(RestoreState.RUNNING_QUEUE);
4706 }
4707
4708 void executeNextState(RestoreState nextState) {
4709 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4710 + this + " nextState=" + nextState);
4711 mCurrentState = nextState;
4712 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4713 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004714 }
4715 }
4716
Christopher Tate44a27902010-01-27 17:15:49 -08004717 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004718 IBackupTransport mTransport;
4719 PackageInfo mPackage;
4720
Christopher Tate44a27902010-01-27 17:15:49 -08004721 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004722 mTransport = transport;
4723 mPackage = packageInfo;
4724 }
4725
Christopher Tateee0e78a2009-07-02 11:17:03 -07004726 public void run() {
4727 try {
4728 // Clear the on-device backup state to ensure a full backup next time
4729 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4730 File stateFile = new File(stateDir, mPackage.packageName);
4731 stateFile.delete();
4732
4733 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004734 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004735 mTransport.clearBackupData(mPackage);
4736 } catch (RemoteException e) {
4737 // can't happen; the transport is local
Christopher Tate0abf6a02012-03-23 17:45:15 -07004738 } catch (Exception e) {
4739 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004740 } finally {
4741 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004742 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004743 mTransport.finishBackup();
4744 } catch (RemoteException e) {
4745 // can't happen; the transport is local
4746 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004747
4748 // Last but not least, release the cpu
4749 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004750 }
4751 }
4752 }
4753
Christopher Tate44a27902010-01-27 17:15:49 -08004754 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004755 HashSet<String> mQueue;
4756
Christopher Tate44a27902010-01-27 17:15:49 -08004757 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004758 mQueue = transportNames;
4759 }
4760
Christopher Tate4cc86e12009-09-21 19:36:51 -07004761 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004762 try {
4763 for (String transportName : mQueue) {
4764 IBackupTransport transport = getTransport(transportName);
4765 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004766 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004767 continue;
4768 }
4769
Joe Onorato8a9b2202010-02-26 18:56:32 -08004770 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004771 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004772 long startRealtime = SystemClock.elapsedRealtime();
4773 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004774
Christopher Tate4cc86e12009-09-21 19:36:51 -07004775 if (status == BackupConstants.TRANSPORT_OK) {
4776 status = transport.finishBackup();
4777 }
4778
4779 // Okay, the wipe really happened. Clean up our local bookkeeping.
4780 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004781 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004782 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004783 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004784 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004785 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004786 synchronized (mQueueLock) {
4787 recordInitPendingLocked(false, transportName);
4788 }
Dan Egnor726247c2009-09-29 19:12:31 -07004789 } else {
4790 // If this didn't work, requeue this one and try again
4791 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004792 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004793 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004794 synchronized (mQueueLock) {
4795 recordInitPendingLocked(true, transportName);
4796 }
4797 // do this via another alarm to make sure of the wakelock states
4798 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004799 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004800 + transportName + " resched in " + delay);
4801 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4802 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004803 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004804 }
4805 } catch (RemoteException e) {
4806 // can't happen; the transports are local
4807 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004808 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004809 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004810 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004811 mWakelock.release();
4812 }
4813 }
4814 }
4815
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004816 private void dataChangedImpl(String packageName) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004817 HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004818 dataChangedImpl(packageName, targets);
4819 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004820
Christopher Tatea3d55342012-03-27 13:16:18 -07004821 private void dataChangedImpl(String packageName, HashSet<String> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004822 // Record that we need a backup pass for the caller. Since multiple callers
4823 // may share a uid, we need to note all candidates within that uid and schedule
4824 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004825 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004826
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004827 if (targets == null) {
4828 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4829 + " uid=" + Binder.getCallingUid());
4830 return;
4831 }
4832
4833 synchronized (mQueueLock) {
4834 // Note that this client has made data changes that need to be backed up
Christopher Tatea3d55342012-03-27 13:16:18 -07004835 if (targets.contains(packageName)) {
4836 // Add the caller to the set of pending backups. If there is
4837 // one already there, then overwrite it, but no harm done.
4838 BackupRequest req = new BackupRequest(packageName);
4839 if (mPendingBackups.put(packageName, req) == null) {
4840 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08004841
Christopher Tatea3d55342012-03-27 13:16:18 -07004842 // Journal this request in case of crash. The put()
4843 // operation returned null when this package was not already
4844 // in the set; we want to avoid touching the disk redundantly.
4845 writeToJournalLocked(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004846
Christopher Tatea3d55342012-03-27 13:16:18 -07004847 if (MORE_DEBUG) {
4848 int numKeys = mPendingBackups.size();
4849 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4850 for (BackupRequest b : mPendingBackups.values()) {
4851 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004852 }
4853 }
4854 }
4855 }
4856 }
4857 }
4858
4859 // Note: packageName is currently unused, but may be in the future
Christopher Tatea3d55342012-03-27 13:16:18 -07004860 private HashSet<String> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004861 // If the caller does not hold the BACKUP permission, it can only request a
4862 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004863 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004864 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004865 synchronized (mBackupParticipants) {
4866 return mBackupParticipants.get(Binder.getCallingUid());
4867 }
4868 }
4869
4870 // a caller with full permission can ask to back up any participating app
4871 // !!! TODO: allow backup of ANY app?
Christopher Tatea3d55342012-03-27 13:16:18 -07004872 HashSet<String> targets = new HashSet<String>();
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004873 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004874 int N = mBackupParticipants.size();
4875 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004876 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tate63d27002009-06-16 17:16:42 -07004877 if (s != null) {
4878 targets.addAll(s);
4879 }
4880 }
4881 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004882 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004883 }
Christopher Tate46758122009-05-06 11:22:00 -07004884
Christopher Tatecde87f42009-06-12 12:55:53 -07004885 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004886 RandomAccessFile out = null;
4887 try {
4888 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4889 out = new RandomAccessFile(mJournal, "rws");
4890 out.seek(out.length());
4891 out.writeUTF(str);
4892 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004893 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004894 mJournal = null;
4895 } finally {
4896 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004897 }
4898 }
4899
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004900 // ----- IBackupManager binder interface -----
4901
4902 public void dataChanged(final String packageName) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004903 final int callingUserHandle = UserHandle.getCallingUserId();
4904 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07004905 // App is running under a non-owner user profile. For now, we do not back
4906 // up data from secondary user profiles.
4907 // TODO: backups for all user profiles.
4908 if (MORE_DEBUG) {
4909 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
4910 + callingUserHandle);
4911 }
4912 return;
4913 }
4914
Christopher Tatea3d55342012-03-27 13:16:18 -07004915 final HashSet<String> targets = dataChangedTargets(packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004916 if (targets == null) {
4917 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4918 + " uid=" + Binder.getCallingUid());
4919 return;
4920 }
4921
4922 mBackupHandler.post(new Runnable() {
4923 public void run() {
4924 dataChangedImpl(packageName, targets);
4925 }
4926 });
4927 }
4928
Christopher Tateee0e78a2009-07-02 11:17:03 -07004929 // Clear the given package's backup data from the current transport
4930 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004931 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004932 PackageInfo info;
4933 try {
4934 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4935 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004936 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004937 return;
4938 }
4939
4940 // If the caller does not hold the BACKUP permission, it can only request a
4941 // wipe of its own backed-up data.
Christopher Tatea3d55342012-03-27 13:16:18 -07004942 HashSet<String> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004943 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004944 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4945 apps = mBackupParticipants.get(Binder.getCallingUid());
4946 } else {
4947 // a caller with full permission can ask to back up any participating app
4948 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004949 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tatea3d55342012-03-27 13:16:18 -07004950 apps = new HashSet<String>();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004951 int N = mBackupParticipants.size();
4952 for (int i = 0; i < N; i++) {
Christopher Tatea3d55342012-03-27 13:16:18 -07004953 HashSet<String> s = mBackupParticipants.valueAt(i);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004954 if (s != null) {
4955 apps.addAll(s);
4956 }
4957 }
4958 }
4959
Christopher Tatea3d55342012-03-27 13:16:18 -07004960 // Is the given app an available participant?
4961 if (apps.contains(packageName)) {
4962 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
4963 // found it; fire off the clear request
4964 synchronized (mQueueLock) {
4965 long oldId = Binder.clearCallingIdentity();
4966 mWakelock.acquire();
4967 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4968 new ClearParams(getTransport(mCurrentTransport), info));
4969 mBackupHandler.sendMessage(msg);
4970 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004971 }
4972 }
4973 }
4974
Christopher Tateace7f092009-06-15 18:07:25 -07004975 // Run a backup pass immediately for any applications that have declared
4976 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004977 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004978 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004979
Joe Onorato8a9b2202010-02-26 18:56:32 -08004980 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004981 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004982 // Because the alarms we are using can jitter, and we want an *immediate*
4983 // backup pass to happen, we restart the timer beginning with "next time,"
4984 // then manually fire the backup trigger intent ourselves.
4985 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004986 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004987 mRunBackupIntent.send();
4988 } catch (PendingIntent.CanceledException e) {
4989 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004990 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004991 }
Christopher Tate46758122009-05-06 11:22:00 -07004992 }
4993 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004994
Christopher Tated2c0cd42011-09-15 15:51:29 -07004995 boolean deviceIsProvisioned() {
4996 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -07004997 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004998 }
4999
Christopher Tate4a627c72011-04-01 14:43:32 -07005000 // Run a *full* backup pass for the given package, writing the resulting data stream
5001 // to the supplied file descriptor. This method is synchronous and does not return
5002 // to the caller until the backup has been completed.
5003 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005004 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005005 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5006
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005007 final int callingUserHandle = UserHandle.getCallingUserId();
5008 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005009 throw new IllegalStateException("Backup supported only for the device owner");
5010 }
5011
Christopher Tate4a627c72011-04-01 14:43:32 -07005012 // Validate
5013 if (!doAllApps) {
5014 if (!includeShared) {
5015 // If we're backing up shared data (sdcard or equivalent), then we can run
5016 // without any supplied app names. Otherwise, we'd be doing no work, so
5017 // report the error.
5018 if (pkgList == null || pkgList.length == 0) {
5019 throw new IllegalArgumentException(
5020 "Backup requested but neither shared nor any apps named");
5021 }
5022 }
5023 }
5024
Christopher Tate4a627c72011-04-01 14:43:32 -07005025 long oldId = Binder.clearCallingIdentity();
5026 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005027 // Doesn't make sense to do a full backup prior to setup
5028 if (!deviceIsProvisioned()) {
5029 Slog.i(TAG, "Full backup not supported before setup");
5030 return;
5031 }
5032
5033 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5034 + " shared=" + includeShared + " all=" + doAllApps
5035 + " pkgs=" + pkgList);
5036 Slog.i(TAG, "Beginning full backup...");
5037
Christopher Tate4a627c72011-04-01 14:43:32 -07005038 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07005039 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07005040 final int token = generateToken();
5041 synchronized (mFullConfirmations) {
5042 mFullConfirmations.put(token, params);
5043 }
5044
Christopher Tate75a99702011-05-18 16:28:19 -07005045 // start up the confirmation UI
5046 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5047 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5048 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07005049 mFullConfirmations.delete(token);
5050 return;
5051 }
Christopher Tate75a99702011-05-18 16:28:19 -07005052
5053 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07005054 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5055
5056 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005057 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005058
5059 // wait for the backup to be performed
5060 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5061 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005062 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005063 try {
5064 fd.close();
5065 } catch (IOException e) {
5066 // just eat it
5067 }
Christopher Tate75a99702011-05-18 16:28:19 -07005068 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005069 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005070 }
Christopher Tate75a99702011-05-18 16:28:19 -07005071 }
5072
5073 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005074 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005075
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005076 final int callingUserHandle = UserHandle.getCallingUserId();
5077 if (callingUserHandle != UserHandle.USER_OWNER) {
Christopher Tateaac71ff2012-08-13 17:36:14 -07005078 throw new IllegalStateException("Restore supported only for the device owner");
5079 }
5080
Christopher Tate75a99702011-05-18 16:28:19 -07005081 long oldId = Binder.clearCallingIdentity();
5082
5083 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005084 // Check whether the device has been provisioned -- we don't handle
5085 // full restores prior to completing the setup process.
5086 if (!deviceIsProvisioned()) {
5087 Slog.i(TAG, "Full restore not permitted before setup");
5088 return;
5089 }
5090
5091 Slog.i(TAG, "Beginning full restore...");
5092
Christopher Tate75a99702011-05-18 16:28:19 -07005093 FullRestoreParams params = new FullRestoreParams(fd);
5094 final int token = generateToken();
5095 synchronized (mFullConfirmations) {
5096 mFullConfirmations.put(token, params);
5097 }
5098
5099 // start up the confirmation UI
5100 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5101 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5102 Slog.e(TAG, "Unable to launch full restore confirmation");
5103 mFullConfirmations.delete(token);
5104 return;
5105 }
5106
5107 // make sure the screen is lit for the user interaction
5108 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5109
5110 // start the confirmation countdown
5111 startConfirmationTimeout(token, params);
5112
5113 // wait for the restore to be performed
5114 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5115 waitForCompletion(params);
5116 } finally {
5117 try {
5118 fd.close();
5119 } catch (IOException e) {
5120 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5121 }
5122 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005123 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005124 }
5125 }
5126
5127 boolean startConfirmationUi(int token, String action) {
5128 try {
5129 Intent confIntent = new Intent(action);
5130 confIntent.setClassName("com.android.backupconfirm",
5131 "com.android.backupconfirm.BackupRestoreConfirmation");
5132 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5133 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5134 mContext.startActivity(confIntent);
5135 } catch (ActivityNotFoundException e) {
5136 return false;
5137 }
5138 return true;
5139 }
5140
5141 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005142 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005143 + TIMEOUT_FULL_CONFIRMATION + " millis");
5144 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5145 token, 0, params);
5146 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005147 }
5148
5149 void waitForCompletion(FullParams params) {
5150 synchronized (params.latch) {
5151 while (params.latch.get() == false) {
5152 try {
5153 params.latch.wait();
5154 } catch (InterruptedException e) { /* never interrupted */ }
5155 }
5156 }
5157 }
5158
5159 void signalFullBackupRestoreCompletion(FullParams params) {
5160 synchronized (params.latch) {
5161 params.latch.set(true);
5162 params.latch.notifyAll();
5163 }
5164 }
5165
5166 // Confirm that the previously-requested full backup/restore operation can proceed. This
5167 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005168 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005169 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005170 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005171 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5172 + " allow=" + allow);
5173
5174 // TODO: possibly require not just this signature-only permission, but even
5175 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005176 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005177
5178 long oldId = Binder.clearCallingIdentity();
5179 try {
5180
5181 FullParams params;
5182 synchronized (mFullConfirmations) {
5183 params = mFullConfirmations.get(token);
5184 if (params != null) {
5185 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5186 mFullConfirmations.delete(token);
5187
5188 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005189 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005190 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005191 : MSG_RUN_FULL_RESTORE;
5192
Christopher Tate728a1c42011-07-28 18:03:03 -07005193 params.observer = observer;
5194 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005195
5196 boolean isEncrypted;
5197 try {
5198 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5199 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5200 } catch (RemoteException e) {
5201 // couldn't contact the mount service; fail "safe" and assume encryption
5202 Slog.e(TAG, "Unable to contact mount service!");
5203 isEncrypted = true;
5204 }
5205 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005206
Christopher Tate75a99702011-05-18 16:28:19 -07005207 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005208 mWakelock.acquire();
5209 Message msg = mBackupHandler.obtainMessage(verb, params);
5210 mBackupHandler.sendMessage(msg);
5211 } else {
5212 Slog.w(TAG, "User rejected full backup/restore operation");
5213 // indicate completion without having actually transferred any data
5214 signalFullBackupRestoreCompletion(params);
5215 }
5216 } else {
5217 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5218 }
5219 }
5220 } finally {
5221 Binder.restoreCallingIdentity(oldId);
5222 }
5223 }
5224
Christopher Tate8031a3d2009-07-06 16:36:05 -07005225 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005226 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005228 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005229
Joe Onorato8a9b2202010-02-26 18:56:32 -08005230 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005231
Christopher Tate6ef58a12009-06-29 14:56:28 -07005232 boolean wasEnabled = mEnabled;
5233 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005234 Settings.Secure.putInt(mContext.getContentResolver(),
5235 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005236 mEnabled = enable;
5237 }
5238
Christopher Tate49401dd2009-07-01 12:34:29 -07005239 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005240 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005241 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005242 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005243 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005244 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005245 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005246
Christopher Tateb6787f22009-07-02 17:40:45 -07005247 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005248
5249 // This also constitutes an opt-out, so we wipe any data for
5250 // this device from the backend. We start that process with
5251 // an alarm in order to guarantee wakelock states.
5252 if (wasEnabled && mProvisioned) {
5253 // NOTE: we currently flush every registered transport, not just
5254 // the currently-active one.
5255 HashSet<String> allTransports;
5256 synchronized (mTransports) {
5257 allTransports = new HashSet<String>(mTransports.keySet());
5258 }
5259 // build the set of transports for which we are posting an init
5260 for (String transport : allTransports) {
5261 recordInitPendingLocked(true, transport);
5262 }
5263 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5264 mRunInitIntent);
5265 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005266 }
5267 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005268 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005269
Christopher Tatecce9da52010-02-03 15:11:15 -08005270 // Enable/disable automatic restore of app data at install time
5271 public void setAutoRestore(boolean doAutoRestore) {
5272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005273 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005274
Joe Onorato8a9b2202010-02-26 18:56:32 -08005275 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005276
5277 synchronized (this) {
5278 Settings.Secure.putInt(mContext.getContentResolver(),
5279 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5280 mAutoRestore = doAutoRestore;
5281 }
5282 }
5283
Christopher Tate8031a3d2009-07-06 16:36:05 -07005284 // Mark the backup service as having been provisioned
5285 public void setBackupProvisioned(boolean available) {
5286 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5287 "setBackupProvisioned");
Christopher Tate97ea1222012-05-17 14:59:41 -07005288 /*
5289 * This is now a no-op; provisioning is simply the device's own setup state.
5290 */
Christopher Tate8031a3d2009-07-06 16:36:05 -07005291 }
5292
5293 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005294 // We used to use setInexactRepeating(), but that may be linked to
5295 // backups running at :00 more often than not, creating load spikes.
5296 // Schedule at an exact time for now, and also add a bit of "fuzz".
5297
5298 Random random = new Random();
5299 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5300 random.nextInt(FUZZ_MILLIS);
5301 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5302 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005303 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005304 }
5305
Christopher Tate6ef58a12009-06-29 14:56:28 -07005306 // Report whether the backup mechanism is currently enabled
5307 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005308 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005309 return mEnabled; // no need to synchronize just to read it
5310 }
5311
Christopher Tate91717492009-06-26 21:07:13 -07005312 // Report the name of the currently active transport
5313 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005315 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005316 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005317 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005318 }
5319
Christopher Tate91717492009-06-26 21:07:13 -07005320 // Report all known, available backup transports
5321 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005323
Christopher Tate91717492009-06-26 21:07:13 -07005324 String[] list = null;
5325 ArrayList<String> known = new ArrayList<String>();
5326 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5327 if (entry.getValue() != null) {
5328 known.add(entry.getKey());
5329 }
5330 }
5331
5332 if (known.size() > 0) {
5333 list = new String[known.size()];
5334 known.toArray(list);
5335 }
5336 return list;
5337 }
5338
5339 // Select which transport to use for the next backup operation. If the given
5340 // name is not one of the available transports, no action is taken and the method
5341 // returns null.
5342 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005344
5345 synchronized (mTransports) {
5346 String prevTransport = null;
5347 if (mTransports.get(transport) != null) {
5348 prevTransport = mCurrentTransport;
5349 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005350 Settings.Secure.putString(mContext.getContentResolver(),
5351 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005352 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005353 + " returning " + prevTransport);
5354 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005355 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005356 }
5357 return prevTransport;
5358 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005359 }
5360
Christopher Tatef5e1c292010-12-08 18:40:26 -08005361 // Supply the configuration Intent for the given transport. If the name is not one
5362 // of the available transports, or if the transport does not supply any configuration
5363 // UI, the method returns null.
5364 public Intent getConfigurationIntent(String transportName) {
5365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5366 "getConfigurationIntent");
5367
5368 synchronized (mTransports) {
5369 final IBackupTransport transport = mTransports.get(transportName);
5370 if (transport != null) {
5371 try {
5372 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005373 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005374 + intent);
5375 return intent;
5376 } catch (RemoteException e) {
5377 /* fall through to return null */
5378 }
5379 }
5380 }
5381
5382 return null;
5383 }
5384
5385 // Supply the configuration summary string for the given transport. If the name is
5386 // not one of the available transports, or if the transport does not supply any
5387 // summary / destination string, the method can return null.
5388 //
5389 // This string is used VERBATIM as the summary text of the relevant Settings item!
5390 public String getDestinationString(String transportName) {
5391 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005392 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005393
5394 synchronized (mTransports) {
5395 final IBackupTransport transport = mTransports.get(transportName);
5396 if (transport != null) {
5397 try {
5398 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005399 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005400 return text;
5401 } catch (RemoteException e) {
5402 /* fall through to return null */
5403 }
5404 }
5405 }
5406
5407 return null;
5408 }
5409
Christopher Tate043dadc2009-06-02 16:11:00 -07005410 // Callback: a requested backup agent has been instantiated. This should only
5411 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005412 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005413 synchronized(mAgentConnectLock) {
5414 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005415 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005416 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5417 mConnectedAgent = agent;
5418 mConnecting = false;
5419 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005420 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005421 + " claiming agent connected");
5422 }
5423 mAgentConnectLock.notifyAll();
5424 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005425 }
5426
5427 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5428 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005429 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005430 public void agentDisconnected(String packageName) {
5431 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005432 synchronized(mAgentConnectLock) {
5433 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5434 mConnectedAgent = null;
5435 mConnecting = false;
5436 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005437 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005438 + " claiming agent disconnected");
5439 }
5440 mAgentConnectLock.notifyAll();
5441 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005442 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005443
Christopher Tate1bb69062010-02-19 17:02:12 -08005444 // An application being installed will need a restore pass, then the Package Manager
5445 // will need to be told when the restore is finished.
5446 public void restoreAtInstall(String packageName, int token) {
5447 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005448 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005449 + " attemping install-time restore");
5450 return;
5451 }
5452
5453 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005454 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tatee82f68d2012-10-23 15:07:38 -07005455 + " token=" + Integer.toHexString(token)
5456 + " restoreSet=" + Long.toHexString(restoreSet));
Christopher Tate1bb69062010-02-19 17:02:12 -08005457
Christopher Tatef0872722010-02-25 15:22:48 -08005458 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005459 // okay, we're going to attempt a restore of this package from this restore set.
5460 // The eventual message back into the Package Manager to run the post-install
5461 // steps for 'token' will be issued from the restore handling code.
5462
5463 // We can use a synthetic PackageInfo here because:
5464 // 1. We know it's valid, since the Package Manager supplied the name
5465 // 2. Only the packageName field will be used by the restore code
5466 PackageInfo pkg = new PackageInfo();
5467 pkg.packageName = packageName;
5468
5469 mWakelock.acquire();
5470 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5471 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005472 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005473 mBackupHandler.sendMessage(msg);
5474 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005475 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5476 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005477 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005478 try {
5479 mPackageManagerBinder.finishPackageInstall(token);
5480 } catch (RemoteException e) { /* can't happen */ }
5481 }
5482 }
5483
Christopher Tate8c850b72009-06-07 19:33:20 -07005484 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005485 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5486 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5487 + " transport=" + transport);
5488
5489 boolean needPermission = true;
5490 if (transport == null) {
5491 transport = mCurrentTransport;
5492
5493 if (packageName != null) {
5494 PackageInfo app = null;
5495 try {
5496 app = mPackageManager.getPackageInfo(packageName, 0);
5497 } catch (NameNotFoundException nnf) {
5498 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5499 throw new IllegalArgumentException("Package " + packageName + " not found");
5500 }
5501
5502 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5503 // So: using the current active transport, and the caller has asked
5504 // that its own package will be restored. In this narrow use case
5505 // we do not require the caller to hold the permission.
5506 needPermission = false;
5507 }
5508 }
5509 }
5510
5511 if (needPermission) {
5512 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5513 "beginRestoreSession");
5514 } else {
5515 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5516 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005517
5518 synchronized(this) {
5519 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005520 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005521 return null;
5522 }
Chris Tate44ab8452010-11-16 15:10:49 -08005523 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005524 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005525 }
5526 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005527 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005528
Christopher Tate73a3cb32010-12-13 18:27:26 -08005529 void clearRestoreSession(ActiveRestoreSession currentSession) {
5530 synchronized(this) {
5531 if (currentSession != mActiveRestoreSession) {
5532 Slog.e(TAG, "ending non-current restore session");
5533 } else {
5534 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5535 mActiveRestoreSession = null;
5536 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5537 }
5538 }
5539 }
5540
Christopher Tate44a27902010-01-27 17:15:49 -08005541 // Note that a currently-active backup agent has notified us that it has
5542 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005543 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005544 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005545 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5546 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005547 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005548 op = mCurrentOperations.get(token);
5549 if (op != null) {
5550 op.state = OP_ACKNOWLEDGED;
5551 }
Christopher Tate44a27902010-01-27 17:15:49 -08005552 mCurrentOpLock.notifyAll();
5553 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005554
5555 // The completion callback, if any, is invoked on the handler
5556 if (op != null && op.callback != null) {
5557 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5558 mBackupHandler.sendMessage(msg);
5559 }
Christopher Tate44a27902010-01-27 17:15:49 -08005560 }
5561
Christopher Tate9b3905c2009-06-08 15:24:01 -07005562 // ----- Restore session -----
5563
Christopher Tate80202c82010-01-25 19:37:47 -08005564 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005565 private static final String TAG = "RestoreSession";
5566
Chris Tate44ab8452010-11-16 15:10:49 -08005567 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005568 private IBackupTransport mRestoreTransport = null;
5569 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005570 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005571
Chris Tate44ab8452010-11-16 15:10:49 -08005572 ActiveRestoreSession(String packageName, String transport) {
5573 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005574 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005575 }
5576
5577 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005578 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005579 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005580 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005581 if (observer == null) {
5582 throw new IllegalArgumentException("Observer must not be null");
5583 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005584
Christopher Tate73a3cb32010-12-13 18:27:26 -08005585 if (mEnded) {
5586 throw new IllegalStateException("Restore session already ended");
5587 }
5588
Christopher Tate1bb69062010-02-19 17:02:12 -08005589 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005590 try {
Christopher Tate43383042009-07-13 15:17:13 -07005591 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005592 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005593 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005594 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005595 // spin off the transport request to our service thread
5596 mWakelock.acquire();
5597 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5598 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5599 mBackupHandler.sendMessage(msg);
5600 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005601 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005602 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005603 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005604 } finally {
5605 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005606 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005607 }
5608
Christopher Tate84725812010-02-04 15:52:40 -08005609 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005610 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5611 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005612
Chris Tate44ab8452010-11-16 15:10:49 -08005613 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005614 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005615
Christopher Tate73a3cb32010-12-13 18:27:26 -08005616 if (mEnded) {
5617 throw new IllegalStateException("Restore session already ended");
5618 }
5619
Dan Egnor0084da52009-07-29 12:57:16 -07005620 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005621 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5622 return -1;
5623 }
5624
5625 if (mPackageName != null) {
5626 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005627 return -1;
5628 }
5629
Christopher Tate21ab6a52009-09-24 18:01:46 -07005630 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005631 for (int i = 0; i < mRestoreSets.length; i++) {
5632 if (token == mRestoreSets[i].token) {
5633 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005634 mWakelock.acquire();
5635 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005636 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005637 mBackupHandler.sendMessage(msg);
5638 Binder.restoreCallingIdentity(oldId);
5639 return 0;
5640 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005641 }
5642 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005643
Joe Onorato8a9b2202010-02-26 18:56:32 -08005644 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005645 return -1;
5646 }
5647
Christopher Tate284f1bb2011-07-07 14:31:18 -07005648 public synchronized int restoreSome(long token, IRestoreObserver observer,
5649 String[] packages) {
5650 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5651 "performRestore");
5652
5653 if (DEBUG) {
5654 StringBuilder b = new StringBuilder(128);
5655 b.append("restoreSome token=");
5656 b.append(Long.toHexString(token));
5657 b.append(" observer=");
5658 b.append(observer.toString());
5659 b.append(" packages=");
5660 if (packages == null) {
5661 b.append("null");
5662 } else {
5663 b.append('{');
5664 boolean first = true;
5665 for (String s : packages) {
5666 if (!first) {
5667 b.append(", ");
5668 } else first = false;
5669 b.append(s);
5670 }
5671 b.append('}');
5672 }
5673 Slog.d(TAG, b.toString());
5674 }
5675
5676 if (mEnded) {
5677 throw new IllegalStateException("Restore session already ended");
5678 }
5679
5680 if (mRestoreTransport == null || mRestoreSets == null) {
5681 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5682 return -1;
5683 }
5684
5685 if (mPackageName != null) {
5686 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5687 return -1;
5688 }
5689
5690 synchronized (mQueueLock) {
5691 for (int i = 0; i < mRestoreSets.length; i++) {
5692 if (token == mRestoreSets[i].token) {
5693 long oldId = Binder.clearCallingIdentity();
5694 mWakelock.acquire();
5695 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5696 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5697 packages, true);
5698 mBackupHandler.sendMessage(msg);
5699 Binder.restoreCallingIdentity(oldId);
5700 return 0;
5701 }
5702 }
5703 }
5704
5705 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5706 return -1;
5707 }
5708
Christopher Tate84725812010-02-04 15:52:40 -08005709 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005710 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005711
Christopher Tate73a3cb32010-12-13 18:27:26 -08005712 if (mEnded) {
5713 throw new IllegalStateException("Restore session already ended");
5714 }
5715
Chris Tate44ab8452010-11-16 15:10:49 -08005716 if (mPackageName != null) {
5717 if (! mPackageName.equals(packageName)) {
5718 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5719 + " on session for package " + mPackageName);
5720 return -1;
5721 }
5722 }
5723
Christopher Tate84725812010-02-04 15:52:40 -08005724 PackageInfo app = null;
5725 try {
5726 app = mPackageManager.getPackageInfo(packageName, 0);
5727 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005728 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005729 return -1;
5730 }
5731
5732 // If the caller is not privileged and is not coming from the target
5733 // app's uid, throw a permission exception back to the caller.
5734 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5735 Binder.getCallingPid(), Binder.getCallingUid());
5736 if ((perm == PackageManager.PERMISSION_DENIED) &&
5737 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005738 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005739 + " or calling uid=" + Binder.getCallingUid());
5740 throw new SecurityException("No permission to restore other packages");
5741 }
5742
Christopher Tate7d411a32010-02-26 11:27:08 -08005743 // If the package has no backup agent, we obviously cannot proceed
5744 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005745 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005746 return -1;
5747 }
5748
Christopher Tate84725812010-02-04 15:52:40 -08005749 // So far so good; we're allowed to try to restore this package. Now
5750 // check whether there is data for it in the current dataset, falling back
5751 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005752 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005753
5754 // If we didn't come up with a place to look -- no ancestral dataset and
5755 // the app has never been backed up from this device -- there's nothing
5756 // to do but return failure.
5757 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005758 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005759 return -1;
5760 }
5761
5762 // Ready to go: enqueue the restore request and claim success
5763 long oldId = Binder.clearCallingIdentity();
5764 mWakelock.acquire();
5765 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005766 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005767 mBackupHandler.sendMessage(msg);
5768 Binder.restoreCallingIdentity(oldId);
5769 return 0;
5770 }
5771
Christopher Tate73a3cb32010-12-13 18:27:26 -08005772 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5773 class EndRestoreRunnable implements Runnable {
5774 BackupManagerService mBackupManager;
5775 ActiveRestoreSession mSession;
5776
5777 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5778 mBackupManager = manager;
5779 mSession = session;
5780 }
5781
5782 public void run() {
5783 // clean up the session's bookkeeping
5784 synchronized (mSession) {
5785 try {
5786 if (mSession.mRestoreTransport != null) {
5787 mSession.mRestoreTransport.finishRestore();
5788 }
5789 } catch (Exception e) {
5790 Slog.e(TAG, "Error in finishRestore", e);
5791 } finally {
5792 mSession.mRestoreTransport = null;
5793 mSession.mEnded = true;
5794 }
5795 }
5796
5797 // clean up the BackupManagerService side of the bookkeeping
5798 // and cancel any pending timeout message
5799 mBackupManager.clearRestoreSession(mSession);
5800 }
5801 }
5802
Dan Egnor0084da52009-07-29 12:57:16 -07005803 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005804 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005805
Christopher Tate73a3cb32010-12-13 18:27:26 -08005806 if (mEnded) {
5807 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005808 }
5809
Christopher Tate73a3cb32010-12-13 18:27:26 -08005810 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005811 }
5812 }
5813
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005814 @Override
5815 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005816 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5817
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005818 long identityToken = Binder.clearCallingIdentity();
5819 try {
5820 dumpInternal(pw);
5821 } finally {
5822 Binder.restoreCallingIdentity(identityToken);
5823 }
5824 }
5825
5826 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005827 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005828 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005829 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005830 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005831 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005832 if (mBackupRunning) pw.println("Backup currently running");
5833 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005834 + " (now = " + System.currentTimeMillis() + ')');
5835 pw.println(" next scheduled: " + mNextBackupPass);
5836
Christopher Tate91717492009-06-26 21:07:13 -07005837 pw.println("Available transports:");
5838 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005839 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5840 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005841 IBackupTransport transport = getTransport(t);
5842 File dir = new File(mBaseStateDir, transport.transportDirName());
5843 pw.println(" destination: " + transport.currentDestinationString());
5844 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005845 for (File f : dir.listFiles()) {
5846 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5847 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005848 } catch (Exception e) {
5849 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005850 pw.println(" Error: " + e);
5851 }
Christopher Tate91717492009-06-26 21:07:13 -07005852 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005853
5854 pw.println("Pending init: " + mPendingInits.size());
5855 for (String s : mPendingInits) {
5856 pw.println(" " + s);
5857 }
5858
Christopher Tate6de74ff2012-01-17 15:20:32 -08005859 if (DEBUG_BACKUP_TRACE) {
5860 synchronized (mBackupTrace) {
5861 if (!mBackupTrace.isEmpty()) {
5862 pw.println("Most recent backup trace:");
5863 for (String s : mBackupTrace) {
5864 pw.println(" " + s);
5865 }
5866 }
5867 }
5868 }
5869
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005870 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005871 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005872 for (int i=0; i<N; i++) {
5873 int uid = mBackupParticipants.keyAt(i);
5874 pw.print(" uid: ");
5875 pw.println(uid);
Christopher Tatea3d55342012-03-27 13:16:18 -07005876 HashSet<String> participants = mBackupParticipants.valueAt(i);
5877 for (String app: participants) {
5878 pw.println(" " + app);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005879 }
5880 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005881
Christopher Tateb49ceb32010-02-08 16:22:24 -08005882 pw.println("Ancestral packages: "
5883 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005884 if (mAncestralPackages != null) {
5885 for (String pkg : mAncestralPackages) {
5886 pw.println(" " + pkg);
5887 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005888 }
5889
Christopher Tate73e02522009-07-15 14:18:26 -07005890 pw.println("Ever backed up: " + mEverStoredApps.size());
5891 for (String pkg : mEverStoredApps) {
5892 pw.println(" " + pkg);
5893 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005894
5895 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005896 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005897 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005898 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005899 }
5900 }
Christopher Tate487529a2009-04-29 14:03:25 -07005901}