blob: 7b8657a03f260638ce33c41bb9481daca392e3f2 [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 Tate3799bc22009-05-06 16:13:56 -070051import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070052import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070053import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070054import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070055import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070056import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080057import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070058import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080059import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070060import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070061import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070062import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070063import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070064import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070065import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070066import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070068import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070069import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080070import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070071import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080072import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070073import android.util.StringBuilderPrinter;
74
Jason parksa3cdaa52011-01-13 14:15:43 -060075import com.android.internal.backup.BackupConstants;
76import com.android.internal.backup.IBackupTransport;
77import com.android.internal.backup.LocalTransport;
78import com.android.server.PackageManagerBackupAgent.Metadata;
79
Christopher Tate2efd2db2011-07-19 16:32:49 -070080import java.io.BufferedInputStream;
81import java.io.BufferedOutputStream;
82import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070083import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070084import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070085import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070086import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070087import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070088import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080089import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070090import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070091import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070092import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070093import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070094import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070095import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070096import java.security.InvalidAlgorithmParameterException;
97import java.security.InvalidKeyException;
98import java.security.Key;
99import java.security.NoSuchAlgorithmException;
100import java.security.SecureRandom;
101import java.security.spec.InvalidKeySpecException;
102import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700103import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400104import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700105import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700106import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400107import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700108import java.util.HashSet;
109import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700110import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700111import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800112import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700113import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700114import java.util.zip.Deflater;
115import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700116import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700117
Christopher Tate2efd2db2011-07-19 16:32:49 -0700118import javax.crypto.BadPaddingException;
119import javax.crypto.Cipher;
120import javax.crypto.CipherInputStream;
121import javax.crypto.CipherOutputStream;
122import javax.crypto.IllegalBlockSizeException;
123import javax.crypto.NoSuchPaddingException;
124import javax.crypto.SecretKey;
125import javax.crypto.SecretKeyFactory;
126import javax.crypto.spec.IvParameterSpec;
127import javax.crypto.spec.PBEKeySpec;
128import javax.crypto.spec.SecretKeySpec;
129
Christopher Tate487529a2009-04-29 14:03:25 -0700130class BackupManagerService extends IBackupManager.Stub {
131 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700132 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700133 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700134
135 // Name and current contents version of the full-backup manifest file
136 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
137 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700138 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
139 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700140 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate49401dd2009-07-01 12:34:29 -0700142 // How often we perform a backup pass. Privileged external callers can
143 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700144 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700145
Dan Egnorc1c49c02009-10-30 17:35:39 -0700146 // Random variation in backup scheduling time to avoid server load spikes
147 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
148
Christopher Tate8031a3d2009-07-06 16:36:05 -0700149 // The amount of time between the initial provisioning of the device and
150 // the first backup pass.
151 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
152
Christopher Tate45281862010-03-05 15:46:30 -0800153 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
154 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
155 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700156 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700157 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700158 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700159 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700160 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700161 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
162 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800163 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700164 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
165 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700166
Christopher Tate8e294d42011-08-31 20:37:12 -0700167 // backup task state machine tick
168 static final int MSG_BACKUP_RESTORE_STEP = 20;
169 static final int MSG_OP_COMPLETE = 21;
170
Christopher Tatec7b31e32009-06-10 15:49:30 -0700171 // Timeout interval for deciding that a bind or clear-data has taken too long
172 static final long TIMEOUT_INTERVAL = 10 * 1000;
173
Christopher Tate44a27902010-01-27 17:15:49 -0800174 // Timeout intervals for agent backup & restore operations
175 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700176 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700177 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800178 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
179
Christopher Tate2efd2db2011-07-19 16:32:49 -0700180 // User confirmation timeout for a full backup/restore operation. It's this long in
181 // order to give them time to enter the backup password.
182 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700183
Christopher Tate487529a2009-04-29 14:03:25 -0700184 private Context mContext;
185 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800186 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700187 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700188 private PowerManager mPowerManager;
189 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800190 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700191
Christopher Tate73e02522009-07-15 14:18:26 -0700192 boolean mEnabled; // access to this is synchronized on 'this'
193 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800194 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700195 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800196 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
197 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700198 PendingIntent mRunBackupIntent, mRunInitIntent;
199 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700200 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700201 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700202 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700203 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700204 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700205 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700206
Christopher Tatecc55f812011-08-16 16:06:53 -0700207 BackupRequest(String pkgName) {
208 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700209 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700210
211 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700212 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700213 }
Christopher Tate46758122009-05-06 11:22:00 -0700214 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800215 // Backups that we haven't started yet. Keys are package names.
216 HashMap<String,BackupRequest> mPendingBackups
217 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700218
219 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700220 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700221
222 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700223 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700224
Christopher Tate043dadc2009-06-02 16:11:00 -0700225 // The thread performing the sequence of queued backups binds to each app's agent
226 // in succession. Bind notifications are asynchronously delivered through the
227 // Activity Manager; use this lock object to signal when a requested binding has
228 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700229 final Object mAgentConnectLock = new Object();
230 IBackupAgent mConnectedAgent;
231 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700232 volatile long mLastBackupPass;
233 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700234
Christopher Tate55f931a2009-09-29 17:17:34 -0700235 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700236 final Object mClearDataLock = new Object();
237 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700238
Christopher Tate91717492009-06-26 21:07:13 -0700239 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700240 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700241 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700242 String mCurrentTransport;
243 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800244 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700245
Christopher Tate2d449afe2010-03-29 19:14:24 -0700246 class RestoreGetSetsParams {
247 public IBackupTransport transport;
248 public ActiveRestoreSession session;
249 public IRestoreObserver observer;
250
251 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
252 IRestoreObserver _observer) {
253 transport = _transport;
254 session = _session;
255 observer = _observer;
256 }
257 }
258
Christopher Tate73e02522009-07-15 14:18:26 -0700259 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700260 public IBackupTransport transport;
261 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700262 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800263 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800264 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700265 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700266 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800267
268 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700269 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800270 transport = _transport;
271 observer = _obs;
272 token = _token;
273 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800274 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700275 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700276 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800277 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700278
Chris Tate249345b2010-10-29 12:57:04 -0700279 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
280 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700281 transport = _transport;
282 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700283 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800284 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800285 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700286 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700287 filterSet = null;
288 }
289
290 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
291 String[] _filterSet, boolean _needFullBackup) {
292 transport = _transport;
293 observer = _obs;
294 token = _token;
295 pkgInfo = null;
296 pmToken = 0;
297 needFullBackup = _needFullBackup;
298 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700299 }
300 }
301
Christopher Tate73e02522009-07-15 14:18:26 -0700302 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700303 public IBackupTransport transport;
304 public PackageInfo packageInfo;
305
306 ClearParams(IBackupTransport _transport, PackageInfo _info) {
307 transport = _transport;
308 packageInfo = _info;
309 }
310 }
311
Christopher Tate4a627c72011-04-01 14:43:32 -0700312 class FullParams {
313 public ParcelFileDescriptor fd;
314 public final AtomicBoolean latch;
315 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700316 public String curPassword; // filled in by the confirmation step
317 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700318
319 FullParams() {
320 latch = new AtomicBoolean(false);
321 }
322 }
323
324 class FullBackupParams extends FullParams {
325 public boolean includeApks;
326 public boolean includeShared;
327 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700328 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700329 public String[] packages;
330
331 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700332 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700333 fd = output;
334 includeApks = saveApks;
335 includeShared = saveShared;
336 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700337 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700338 packages = pkgList;
339 }
340 }
341
342 class FullRestoreParams extends FullParams {
343 FullRestoreParams(ParcelFileDescriptor input) {
344 fd = input;
345 }
346 }
347
Christopher Tate44a27902010-01-27 17:15:49 -0800348 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
349 // token is the index of the entry in the pending-operations list.
350 static final int OP_PENDING = 0;
351 static final int OP_ACKNOWLEDGED = 1;
352 static final int OP_TIMEOUT = -1;
353
Christopher Tate8e294d42011-08-31 20:37:12 -0700354 class Operation {
355 public int state;
356 public BackupRestoreTask callback;
357
358 Operation(int initialState, BackupRestoreTask callbackObj) {
359 state = initialState;
360 callback = callbackObj;
361 }
362 }
363 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800364 final Object mCurrentOpLock = new Object();
365 final Random mTokenGenerator = new Random();
366
Christopher Tate4a627c72011-04-01 14:43:32 -0700367 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
368
Christopher Tate5cb400b2009-06-25 16:03:14 -0700369 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700370 File mBaseStateDir;
371 File mDataDir;
372 File mJournalDir;
373 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700374
Christopher Tate2efd2db2011-07-19 16:32:49 -0700375 // Backup password, if any, and the file where it's saved. What is stored is not the
376 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
377 // persisted) salt. Validation is performed by running the challenge text through the
378 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
379 // the saved hash string, then the challenge text matches the originally supplied
380 // password text.
381 private final SecureRandom mRng = new SecureRandom();
382 private String mPasswordHash;
383 private File mPasswordHashFile;
384 private byte[] mPasswordSalt;
385
386 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
387 static final int PBKDF2_HASH_ROUNDS = 10000;
388 static final int PBKDF2_KEY_SIZE = 256; // bits
389 static final int PBKDF2_SALT_SIZE = 512; // bits
390 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
391
Christopher Tate84725812010-02-04 15:52:40 -0800392 // Keep a log of all the apps we've ever backed up, and what the
393 // dataset tokens are for both the current backup dataset and
394 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700395 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700396 HashSet<String> mEverStoredApps = new HashSet<String>();
397
Christopher Tateb49ceb32010-02-08 16:22:24 -0800398 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800399 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800400 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800401 long mAncestralToken = 0;
402 long mCurrentToken = 0;
403
Christopher Tate4cc86e12009-09-21 19:36:51 -0700404 // Persistently track the need to do a full init
405 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
406 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700407
Christopher Tate4a627c72011-04-01 14:43:32 -0700408 // Utility: build a new random integer token
409 int generateToken() {
410 int token;
411 do {
412 synchronized (mTokenGenerator) {
413 token = mTokenGenerator.nextInt();
414 }
415 } while (token < 0);
416 return token;
417 }
418
Christopher Tate44a27902010-01-27 17:15:49 -0800419 // ----- Asynchronous backup/restore handler thread -----
420
421 private class BackupHandler extends Handler {
422 public BackupHandler(Looper looper) {
423 super(looper);
424 }
425
426 public void handleMessage(Message msg) {
427
428 switch (msg.what) {
429 case MSG_RUN_BACKUP:
430 {
431 mLastBackupPass = System.currentTimeMillis();
432 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
433
434 IBackupTransport transport = getTransport(mCurrentTransport);
435 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800436 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800437 mWakelock.release();
438 break;
439 }
440
441 // snapshot the pending-backup set and work on that
442 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800443 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800444 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800445 // Do we have any work to do? Construct the work queue
446 // then release the synchronization lock to actually run
447 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800448 if (mPendingBackups.size() > 0) {
449 for (BackupRequest b: mPendingBackups.values()) {
450 queue.add(b);
451 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800452 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800453 mPendingBackups.clear();
454
455 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800456 mJournal = null;
457
Christopher Tate44a27902010-01-27 17:15:49 -0800458 }
459 }
Christopher Tatec61da312010-02-05 10:41:27 -0800460
Christopher Tate8e294d42011-08-31 20:37:12 -0700461 // At this point, we have started a new journal file, and the old
462 // file identity is being passed to the backup processing task.
463 // When it completes successfully, that old journal file will be
464 // deleted. If we crash prior to that, the old journal is parsed
465 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800466 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700467 // Spin up a backup state sequence and set it running
468 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
469 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
470 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800471 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800472 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800473 mWakelock.release();
474 }
Christopher Tate44a27902010-01-27 17:15:49 -0800475 break;
476 }
477
Christopher Tate8e294d42011-08-31 20:37:12 -0700478 case MSG_BACKUP_RESTORE_STEP:
479 {
480 try {
481 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
482 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
483 task.execute();
484 } catch (ClassCastException e) {
485 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
486 }
487 break;
488 }
489
490 case MSG_OP_COMPLETE:
491 {
492 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700493 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
494 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700495 } catch (ClassCastException e) {
496 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
497 }
498 break;
499 }
500
Christopher Tate44a27902010-01-27 17:15:49 -0800501 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700502 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700503 // TODO: refactor full backup to be a looper-based state machine
504 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700505 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700506 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
507 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700508 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700509 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700510 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800511 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700512 }
Christopher Tate44a27902010-01-27 17:15:49 -0800513
514 case MSG_RUN_RESTORE:
515 {
516 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800517 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700518 PerformRestoreTask task = new PerformRestoreTask(
519 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700520 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700521 params.needFullBackup, params.filterSet);
522 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
523 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800524 break;
525 }
526
Christopher Tate75a99702011-05-18 16:28:19 -0700527 case MSG_RUN_FULL_RESTORE:
528 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700529 // TODO: refactor full restore to be a looper-based state machine
530 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700531 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700532 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
533 params.curPassword, params.encryptPassword,
534 params.observer, params.latch);
535 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700536 break;
537 }
538
Christopher Tate44a27902010-01-27 17:15:49 -0800539 case MSG_RUN_CLEAR:
540 {
541 ClearParams params = (ClearParams)msg.obj;
542 (new PerformClearTask(params.transport, params.packageInfo)).run();
543 break;
544 }
545
546 case MSG_RUN_INITIALIZE:
547 {
548 HashSet<String> queue;
549
550 // Snapshot the pending-init queue and work on that
551 synchronized (mQueueLock) {
552 queue = new HashSet<String>(mPendingInits);
553 mPendingInits.clear();
554 }
555
556 (new PerformInitializeTask(queue)).run();
557 break;
558 }
559
Christopher Tate2d449afe2010-03-29 19:14:24 -0700560 case MSG_RUN_GET_RESTORE_SETS:
561 {
562 // Like other async operations, this is entered with the wakelock held
563 RestoreSet[] sets = null;
564 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
565 try {
566 sets = params.transport.getAvailableRestoreSets();
567 // cache the result in the active session
568 synchronized (params.session) {
569 params.session.mRestoreSets = sets;
570 }
571 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
572 } catch (Exception e) {
573 Slog.e(TAG, "Error from transport getting set list");
574 } finally {
575 if (params.observer != null) {
576 try {
577 params.observer.restoreSetsAvailable(sets);
578 } catch (RemoteException re) {
579 Slog.e(TAG, "Unable to report listing to observer");
580 } catch (Exception e) {
581 Slog.e(TAG, "Restore observer threw", e);
582 }
583 }
584
Christopher Tate2a935092011-03-03 17:30:32 -0800585 // Done: reset the session timeout clock
586 removeMessages(MSG_RESTORE_TIMEOUT);
587 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
588
Christopher Tate2d449afe2010-03-29 19:14:24 -0700589 mWakelock.release();
590 }
591 break;
592 }
593
Christopher Tate44a27902010-01-27 17:15:49 -0800594 case MSG_TIMEOUT:
595 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700596 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800597 break;
598 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800599
600 case MSG_RESTORE_TIMEOUT:
601 {
602 synchronized (BackupManagerService.this) {
603 if (mActiveRestoreSession != null) {
604 // Client app left the restore session dangling. We know that it
605 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700606 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800607 // up now.
608 Slog.w(TAG, "Restore session timed out; aborting");
609 post(mActiveRestoreSession.new EndRestoreRunnable(
610 BackupManagerService.this, mActiveRestoreSession));
611 }
612 }
613 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700614
615 case MSG_FULL_CONFIRMATION_TIMEOUT:
616 {
617 synchronized (mFullConfirmations) {
618 FullParams params = mFullConfirmations.get(msg.arg1);
619 if (params != null) {
620 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
621
622 // Release the waiter; timeout == completion
623 signalFullBackupRestoreCompletion(params);
624
625 // Remove the token from the set
626 mFullConfirmations.delete(msg.arg1);
627
628 // Report a timeout to the observer, if any
629 if (params.observer != null) {
630 try {
631 params.observer.onTimeout();
632 } catch (RemoteException e) {
633 /* don't care if the app has gone away */
634 }
635 }
636 } else {
637 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
638 }
639 }
640 break;
641 }
Christopher Tate44a27902010-01-27 17:15:49 -0800642 }
643 }
644 }
645
646 // ----- Main service implementation -----
647
Christopher Tate487529a2009-04-29 14:03:25 -0700648 public BackupManagerService(Context context) {
649 mContext = context;
650 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700651 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700652 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700653
Christopher Tateb6787f22009-07-02 17:40:45 -0700654 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
655 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
656
Christopher Tate44a27902010-01-27 17:15:49 -0800657 mBackupManagerBinder = asInterface(asBinder());
658
659 // spin up the backup/restore handler thread
660 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
661 mHandlerThread.start();
662 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
663
Christopher Tate22b87872009-05-04 16:41:53 -0700664 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700665 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700666 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700667 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700668 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800669 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800670 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800671 // If Encrypted file systems is enabled or disabled, this call will return the
672 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600673 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800674 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700675 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700676
Christopher Tate2efd2db2011-07-19 16:32:49 -0700677 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
678 if (mPasswordHashFile.exists()) {
679 FileInputStream fin = null;
680 DataInputStream in = null;
681 try {
682 fin = new FileInputStream(mPasswordHashFile);
683 in = new DataInputStream(new BufferedInputStream(fin));
684 // integer length of the salt array, followed by the salt,
685 // then the hex pw hash string
686 int saltLen = in.readInt();
687 byte[] salt = new byte[saltLen];
688 in.readFully(salt);
689 mPasswordHash = in.readUTF();
690 mPasswordSalt = salt;
691 } catch (IOException e) {
692 Slog.e(TAG, "Unable to read saved backup pw hash");
693 } finally {
694 try {
695 if (in != null) in.close();
696 if (fin != null) fin.close();
697 } catch (IOException e) {
698 Slog.w(TAG, "Unable to close streams");
699 }
700 }
701 }
702
Christopher Tate4cc86e12009-09-21 19:36:51 -0700703 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700704 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700705 IntentFilter filter = new IntentFilter();
706 filter.addAction(RUN_BACKUP_ACTION);
707 context.registerReceiver(mRunBackupReceiver, filter,
708 android.Manifest.permission.BACKUP, null);
709
710 mRunInitReceiver = new RunInitializeReceiver();
711 filter = new IntentFilter();
712 filter.addAction(RUN_INITIALIZE_ACTION);
713 context.registerReceiver(mRunInitReceiver, filter,
714 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700715
716 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700717 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
718 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
719
Christopher Tate4cc86e12009-09-21 19:36:51 -0700720 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
721 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
722 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
723
Christopher Tatecde87f42009-06-12 12:55:53 -0700724 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700725 mJournalDir = new File(mBaseStateDir, "pending");
726 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700727 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700728
Christopher Tate73e02522009-07-15 14:18:26 -0700729 // Set up the various sorts of package tracking we do
730 initPackageTracking();
731
Christopher Tateabce4e82009-06-18 18:35:32 -0700732 // Build our mapping of uid to backup client services. This implicitly
733 // schedules a backup pass on the Package Manager metadata the first
734 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700735 synchronized (mBackupParticipants) {
736 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700737 }
738
Dan Egnor87a02bc2009-06-17 02:30:10 -0700739 // Set up our transport options and initialize the default transport
740 // TODO: Have transports register themselves somehow?
741 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700742 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700743 ComponentName localName = new ComponentName(context, LocalTransport.class);
744 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700745
Christopher Tate91717492009-06-26 21:07:13 -0700746 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700747 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
748 Settings.Secure.BACKUP_TRANSPORT);
749 if ("".equals(mCurrentTransport)) {
750 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700751 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800752 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700753
754 // Attach to the Google backup transport. When this comes up, it will set
755 // itself as the current transport because we explicitly reset mCurrentTransport
756 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700757 ComponentName transportComponent = new ComponentName("com.google.android.backup",
758 "com.google.android.backup.BackupTransportService");
759 try {
760 // If there's something out there that is supposed to be the Google
761 // backup transport, make sure it's legitimately part of the OS build
762 // and not an app lying about its package name.
763 ApplicationInfo info = mPackageManager.getApplicationInfo(
764 transportComponent.getPackageName(), 0);
765 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
766 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
767 Intent intent = new Intent().setComponent(transportComponent);
768 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
769 } else {
770 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
771 }
772 } catch (PackageManager.NameNotFoundException nnf) {
773 // No such package? No binding.
774 if (DEBUG) Slog.v(TAG, "Google transport not present");
775 }
Christopher Tateaa088442009-06-16 18:25:46 -0700776
Christopher Tatecde87f42009-06-12 12:55:53 -0700777 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700778 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700779 parseLeftoverJournals();
780
Christopher Tateb6787f22009-07-02 17:40:45 -0700781 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700782 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700783
784 // Start the backup passes going
785 setBackupEnabled(areEnabled);
786 }
787
788 private class RunBackupReceiver extends BroadcastReceiver {
789 public void onReceive(Context context, Intent intent) {
790 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700791 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700792 if (mPendingInits.size() > 0) {
793 // If there are pending init operations, we process those
794 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800795 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700796 try {
797 mAlarmManager.cancel(mRunInitIntent);
798 mRunInitIntent.send();
799 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800800 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700801 // can't really do more than bail here
802 }
803 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800804 // Don't run backups now if we're disabled or not yet
805 // fully set up.
806 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800807 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700808
809 // Acquire the wakelock and pass it to the backup thread. it will
810 // be released once backup concludes.
811 mWakelock.acquire();
812
813 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
814 mBackupHandler.sendMessage(msg);
815 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700817 }
818 }
819 }
820 }
821 }
822 }
823
824 private class RunInitializeReceiver extends BroadcastReceiver {
825 public void onReceive(Context context, Intent intent) {
826 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
827 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700829
830 // Acquire the wakelock and pass it to the init thread. it will
831 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700832 mWakelock.acquire();
833
Christopher Tate4cc86e12009-09-21 19:36:51 -0700834 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700835 mBackupHandler.sendMessage(msg);
836 }
837 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700838 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700839 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700840
Christopher Tate73e02522009-07-15 14:18:26 -0700841 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800842 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700843
Christopher Tate84725812010-02-04 15:52:40 -0800844 // Remember our ancestral dataset
845 mTokenFile = new File(mBaseStateDir, "ancestral");
846 try {
847 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800848 int version = tf.readInt();
849 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
850 mAncestralToken = tf.readLong();
851 mCurrentToken = tf.readLong();
852
853 int numPackages = tf.readInt();
854 if (numPackages >= 0) {
855 mAncestralPackages = new HashSet<String>();
856 for (int i = 0; i < numPackages; i++) {
857 String pkgName = tf.readUTF();
858 mAncestralPackages.add(pkgName);
859 }
860 }
861 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800862 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800863 } catch (FileNotFoundException fnf) {
864 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800866 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800868 }
869
Christopher Tatee97e8072009-07-15 16:45:50 -0700870 // Keep a log of what apps we've ever backed up. Because we might have
871 // rebooted in the middle of an operation that was removing something from
872 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700873 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700874 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700875
Christopher Tatee97e8072009-07-15 16:45:50 -0700876 // If we were in the middle of removing something from the ever-backed-up
877 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700878 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700879 if (tempProcessedFile.exists()) {
880 tempProcessedFile.delete();
881 }
882
Dan Egnor852f8e42009-09-30 11:20:45 -0700883 // If there are previous contents, parse them out then start a new
884 // file to continue the recordkeeping.
885 if (mEverStored.exists()) {
886 RandomAccessFile temp = null;
887 RandomAccessFile in = null;
888
889 try {
890 temp = new RandomAccessFile(tempProcessedFile, "rws");
891 in = new RandomAccessFile(mEverStored, "r");
892
893 while (true) {
894 PackageInfo info;
895 String pkg = in.readUTF();
896 try {
897 info = mPackageManager.getPackageInfo(pkg, 0);
898 mEverStoredApps.add(pkg);
899 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700900 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700901 } catch (NameNotFoundException e) {
902 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700903 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700904 }
905 }
906 } catch (EOFException e) {
907 // Once we've rewritten the backup history log, atomically replace the
908 // old one with the new one then reopen the file for continuing use.
909 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700911 }
912 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800913 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700914 } finally {
915 try { if (temp != null) temp.close(); } catch (IOException e) {}
916 try { if (in != null) in.close(); } catch (IOException e) {}
917 }
918 }
919
Christopher Tate73e02522009-07-15 14:18:26 -0700920 // Register for broadcasts about package install, etc., so we can
921 // update the provider list.
922 IntentFilter filter = new IntentFilter();
923 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
924 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700925 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700926 filter.addDataScheme("package");
927 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800928 // Register for events related to sdcard installation.
929 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800930 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
931 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800932 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700933 }
934
Christopher Tatecde87f42009-06-12 12:55:53 -0700935 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700936 for (File f : mJournalDir.listFiles()) {
937 if (mJournal == null || f.compareTo(mJournal) != 0) {
938 // This isn't the current journal, so it must be a leftover. Read
939 // out the package names mentioned there and schedule them for
940 // backup.
941 RandomAccessFile in = null;
942 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400943 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700944 in = new RandomAccessFile(f, "r");
945 while (true) {
946 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400947 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700948 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700949 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700950 } catch (EOFException e) {
951 // no more data; we're done
952 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800953 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700954 } finally {
955 // close/delete the file
956 try { if (in != null) in.close(); } catch (IOException e) {}
957 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700958 }
959 }
960 }
961 }
962
Christopher Tate2efd2db2011-07-19 16:32:49 -0700963 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
964 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
965 }
966
967 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
968 try {
969 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
970 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
971 return keyFactory.generateSecret(ks);
972 } catch (InvalidKeySpecException e) {
973 Slog.e(TAG, "Invalid key spec for PBKDF2!");
974 } catch (NoSuchAlgorithmException e) {
975 Slog.e(TAG, "PBKDF2 unavailable!");
976 }
977 return null;
978 }
979
980 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
981 SecretKey key = buildPasswordKey(pw, salt, rounds);
982 if (key != null) {
983 return byteArrayToHex(key.getEncoded());
984 }
985 return null;
986 }
987
988 private String byteArrayToHex(byte[] data) {
989 StringBuilder buf = new StringBuilder(data.length * 2);
990 for (int i = 0; i < data.length; i++) {
991 buf.append(Byte.toHexString(data[i], true));
992 }
993 return buf.toString();
994 }
995
996 private byte[] hexToByteArray(String digits) {
997 final int bytes = digits.length() / 2;
998 if (2*bytes != digits.length()) {
999 throw new IllegalArgumentException("Hex string must have an even number of digits");
1000 }
1001
1002 byte[] result = new byte[bytes];
1003 for (int i = 0; i < digits.length(); i += 2) {
1004 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1005 }
1006 return result;
1007 }
1008
1009 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1010 char[] mkAsChar = new char[pwBytes.length];
1011 for (int i = 0; i < pwBytes.length; i++) {
1012 mkAsChar[i] = (char) pwBytes[i];
1013 }
1014
1015 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1016 return checksum.getEncoded();
1017 }
1018
1019 // Used for generating random salts or passwords
1020 private byte[] randomBytes(int bits) {
1021 byte[] array = new byte[bits / 8];
1022 mRng.nextBytes(array);
1023 return array;
1024 }
1025
1026 // Backup password management
1027 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1028 if (mPasswordHash == null) {
1029 // no current password case -- require that 'currentPw' be null or empty
1030 if (candidatePw == null || "".equals(candidatePw)) {
1031 return true;
1032 } // else the non-empty candidate does not match the empty stored pw
1033 } else {
1034 // hash the stated current pw and compare to the stored one
1035 if (candidatePw != null && candidatePw.length() > 0) {
1036 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1037 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1038 // candidate hash matches the stored hash -- the password matches
1039 return true;
1040 }
1041 } // else the stored pw is nonempty but the candidate is empty; no match
1042 }
1043 return false;
1044 }
1045
1046 @Override
1047 public boolean setBackupPassword(String currentPw, String newPw) {
1048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1049 "setBackupPassword");
1050
1051 // If the supplied pw doesn't hash to the the saved one, fail
1052 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1053 return false;
1054 }
1055
1056 // Clearing the password is okay
1057 if (newPw == null || newPw.isEmpty()) {
1058 if (mPasswordHashFile.exists()) {
1059 if (!mPasswordHashFile.delete()) {
1060 // Unable to delete the old pw file, so fail
1061 Slog.e(TAG, "Unable to clear backup password");
1062 return false;
1063 }
1064 }
1065 mPasswordHash = null;
1066 mPasswordSalt = null;
1067 return true;
1068 }
1069
1070 try {
1071 // Okay, build the hash of the new backup password
1072 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1073 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1074
1075 OutputStream pwf = null, buffer = null;
1076 DataOutputStream out = null;
1077 try {
1078 pwf = new FileOutputStream(mPasswordHashFile);
1079 buffer = new BufferedOutputStream(pwf);
1080 out = new DataOutputStream(buffer);
1081 // integer length of the salt array, followed by the salt,
1082 // then the hex pw hash string
1083 out.writeInt(salt.length);
1084 out.write(salt);
1085 out.writeUTF(newPwHash);
1086 out.flush();
1087 mPasswordHash = newPwHash;
1088 mPasswordSalt = salt;
1089 return true;
1090 } finally {
1091 if (out != null) out.close();
1092 if (buffer != null) buffer.close();
1093 if (pwf != null) pwf.close();
1094 }
1095 } catch (IOException e) {
1096 Slog.e(TAG, "Unable to set backup password");
1097 }
1098 return false;
1099 }
1100
1101 @Override
1102 public boolean hasBackupPassword() {
1103 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1104 "hasBackupPassword");
1105 return (mPasswordHash != null && mPasswordHash.length() > 0);
1106 }
1107
Christopher Tate4cc86e12009-09-21 19:36:51 -07001108 // Maintain persistent state around whether need to do an initialize operation.
1109 // Must be called with the queue lock held.
1110 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001111 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001112 + " on transport " + transportName);
1113 try {
1114 IBackupTransport transport = getTransport(transportName);
1115 String transportDirName = transport.transportDirName();
1116 File stateDir = new File(mBaseStateDir, transportDirName);
1117 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1118
1119 if (isPending) {
1120 // We need an init before we can proceed with sending backup data.
1121 // Record that with an entry in our set of pending inits, as well as
1122 // journaling it via creation of a sentinel file.
1123 mPendingInits.add(transportName);
1124 try {
1125 (new FileOutputStream(initPendingFile)).close();
1126 } catch (IOException ioe) {
1127 // Something is badly wrong with our permissions; just try to move on
1128 }
1129 } else {
1130 // No more initialization needed; wipe the journal and reset our state.
1131 initPendingFile.delete();
1132 mPendingInits.remove(transportName);
1133 }
1134 } catch (RemoteException e) {
1135 // can't happen; the transport is local
1136 }
1137 }
1138
Christopher Tated55e18a2009-09-21 10:12:59 -07001139 // Reset all of our bookkeeping, in response to having been told that
1140 // the backend data has been wiped [due to idle expiry, for example],
1141 // so we must re-upload all saved settings.
1142 void resetBackupState(File stateFileDir) {
1143 synchronized (mQueueLock) {
1144 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001145 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001146 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001147
Christopher Tate84725812010-02-04 15:52:40 -08001148 mCurrentToken = 0;
1149 writeRestoreTokens();
1150
Christopher Tated55e18a2009-09-21 10:12:59 -07001151 // Remove all the state files
1152 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001153 // ... but don't touch the needs-init sentinel
1154 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1155 sf.delete();
1156 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001157 }
Christopher Tate45597642011-04-04 16:59:21 -07001158 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001159
Christopher Tate45597642011-04-04 16:59:21 -07001160 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001161 synchronized (mBackupParticipants) {
1162 int N = mBackupParticipants.size();
1163 for (int i=0; i<N; i++) {
1164 int uid = mBackupParticipants.keyAt(i);
1165 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1166 for (ApplicationInfo app: participants) {
1167 dataChangedImpl(app.packageName);
1168 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001169 }
1170 }
1171 }
1172
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001173 // Add a transport to our set of available backends. If 'transport' is null, this
1174 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001175 private void registerTransport(String name, IBackupTransport transport) {
1176 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001177 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001178 if (transport != null) {
1179 mTransports.put(name, transport);
1180 } else {
1181 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001182 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001183 mCurrentTransport = null;
1184 }
1185 // Nothing further to do in the unregistration case
1186 return;
1187 }
Christopher Tate91717492009-06-26 21:07:13 -07001188 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001189
1190 // If the init sentinel file exists, we need to be sure to perform the init
1191 // as soon as practical. We also create the state directory at registration
1192 // time to ensure it's present from the outset.
1193 try {
1194 String transportName = transport.transportDirName();
1195 File stateDir = new File(mBaseStateDir, transportName);
1196 stateDir.mkdirs();
1197
1198 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1199 if (initSentinel.exists()) {
1200 synchronized (mQueueLock) {
1201 mPendingInits.add(transportName);
1202
1203 // TODO: pick a better starting time than now + 1 minute
1204 long delay = 1000 * 60; // one minute, in milliseconds
1205 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1206 System.currentTimeMillis() + delay, mRunInitIntent);
1207 }
1208 }
1209 } catch (RemoteException e) {
1210 // can't happen, the transport is local
1211 }
Christopher Tate91717492009-06-26 21:07:13 -07001212 }
1213
Christopher Tate3799bc22009-05-06 16:13:56 -07001214 // ----- Track installation/removal of packages -----
1215 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1216 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001217 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001218
Christopher Tate3799bc22009-05-06 16:13:56 -07001219 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001220 boolean replacing = false;
1221 boolean added = false;
1222 Bundle extras = intent.getExtras();
1223 String pkgList[] = null;
1224 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001225 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1226 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001227 Uri uri = intent.getData();
1228 if (uri == null) {
1229 return;
1230 }
1231 String pkgName = uri.getSchemeSpecificPart();
1232 if (pkgName != null) {
1233 pkgList = new String[] { pkgName };
1234 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001235 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1236 // use the existing "add with replacement" logic
1237 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1238 added = replacing = true;
1239 } else {
1240 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1241 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1242 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001243 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001244 added = true;
1245 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001246 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001247 added = false;
1248 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1249 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001250
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001251 if (pkgList == null || pkgList.length == 0) {
1252 return;
1253 }
1254 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001255 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001256 for (String pkgName : pkgList) {
1257 if (replacing) {
1258 // The package was just upgraded
1259 updatePackageParticipantsLocked(pkgName);
1260 } else {
1261 // The package was just added
1262 addPackageParticipantsLocked(pkgName);
1263 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001264 }
1265 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001266 } else {
1267 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001268 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1269 } else {
1270 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001271 for (String pkgName : pkgList) {
1272 removePackageParticipantsLocked(pkgName);
1273 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001274 }
1275 }
1276 }
1277 }
1278 };
1279
Dan Egnor87a02bc2009-06-17 02:30:10 -07001280 // ----- Track connection to GoogleBackupTransport service -----
1281 ServiceConnection mGoogleConnection = new ServiceConnection() {
1282 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001284 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001285 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001286 }
1287
1288 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001289 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001290 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001291 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001292 }
1293 };
1294
Christopher Tate181fafa2009-05-14 11:12:14 -07001295 // Add the backup agents in the given package to our set of known backup participants.
1296 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001297 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001298 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001299 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001300 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001301 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001302 }
1303
Christopher Tate181fafa2009-05-14 11:12:14 -07001304 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001305 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001306 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001307 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001308 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001309 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001310 + " uid=" + p.applicationInfo.uid
1311 + " killAfterRestore="
1312 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001313 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001314 }
1315 }
1316
Dan Egnorefe52642009-06-24 00:16:33 -07001317 for (PackageInfo pkg : targetPkgs) {
1318 if (packageName == null || pkg.packageName.equals(packageName)) {
1319 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001320 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001321 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001322 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001323 mBackupParticipants.put(uid, set);
1324 }
Dan Egnorefe52642009-06-24 00:16:33 -07001325 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001326
1327 // If we've never seen this app before, schedule a backup for it
1328 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001329 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001330 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001331 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001332 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001333 }
Christopher Tate487529a2009-04-29 14:03:25 -07001334 }
1335 }
1336
Christopher Tate6785dd82009-06-18 15:58:25 -07001337 // Remove the given package's entry from our known active set. If
1338 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001339 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001340 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001341 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001342 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001343 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001344 } else {
1345 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001346 List<PackageInfo> knownPackages = allAgentPackages();
1347 for (PackageInfo pkg : knownPackages) {
1348 allApps.add(pkg.packageName);
1349 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001350 }
1351 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001352 }
1353
Joe Onorato8ad02812009-05-13 01:41:44 -04001354 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001355 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001356 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001357 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001358 + ") removing " + allPackageNames.size() + " entries");
1359 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001360 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001361 }
1362 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001363 for (String pkg : allPackageNames) {
1364 if (packageName == null || pkg.equals(packageName)) {
1365 int uid = -1;
1366 try {
1367 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1368 uid = info.applicationInfo.uid;
1369 } catch (NameNotFoundException e) {
1370 // we don't know this package name, so just skip it for now
1371 continue;
1372 }
1373
Christopher Tate181fafa2009-05-14 11:12:14 -07001374 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001375 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001376 // Find the existing entry with the same package name, and remove it.
1377 // We can't just remove(app) because the instances are different.
1378 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001379 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001380 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001381 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001382 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001383 break;
1384 }
1385 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001386 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001387 mBackupParticipants.delete(uid);
1388 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001389 }
1390 }
1391 }
1392 }
1393
Christopher Tate181fafa2009-05-14 11:12:14 -07001394 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001395 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001396 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001397 int flags = PackageManager.GET_SIGNATURES;
1398 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1399 int N = packages.size();
1400 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001401 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001402 try {
1403 ApplicationInfo app = pkg.applicationInfo;
1404 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001405 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001406 packages.remove(a);
1407 }
1408 else {
1409 // we will need the shared library path, so look that up and store it here
1410 app = mPackageManager.getApplicationInfo(pkg.packageName,
1411 PackageManager.GET_SHARED_LIBRARY_FILES);
1412 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1413 }
1414 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001415 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001416 }
1417 }
Dan Egnorefe52642009-06-24 00:16:33 -07001418 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001419 }
Christopher Tateaa088442009-06-16 18:25:46 -07001420
Christopher Tate3799bc22009-05-06 16:13:56 -07001421 // Reset the given package's known backup participants. Unlike add/remove, the update
1422 // action cannot be passed a null package name.
1423 void updatePackageParticipantsLocked(String packageName) {
1424 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001425 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001426 return;
1427 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001428 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001429
1430 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001431 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001432 List<String> allAppNames = new ArrayList<String>();
1433 for (PackageInfo pkg : allApps) {
1434 allAppNames.add(pkg.packageName);
1435 }
1436 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001437 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001438 }
1439
Christopher Tate84725812010-02-04 15:52:40 -08001440 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001441 // backed up at least once
1442 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001443 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1444
1445 synchronized (mEverStoredApps) {
1446 if (!mEverStoredApps.add(packageName)) return;
1447
1448 RandomAccessFile out = null;
1449 try {
1450 out = new RandomAccessFile(mEverStored, "rws");
1451 out.seek(out.length());
1452 out.writeUTF(packageName);
1453 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001454 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001455 } finally {
1456 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001457 }
1458 }
1459 }
1460
Christopher Tatee97e8072009-07-15 16:45:50 -07001461 // Remove our awareness of having ever backed up the given package
1462 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001463 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1464 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001465
Dan Egnor852f8e42009-09-30 11:20:45 -07001466 synchronized (mEverStoredApps) {
1467 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1468 // we'll recognize on initialization time that the package no longer
1469 // exists and fix it up then.
1470 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1471 RandomAccessFile known = null;
1472 try {
1473 known = new RandomAccessFile(tempKnownFile, "rws");
1474 mEverStoredApps.remove(packageName);
1475 for (String s : mEverStoredApps) {
1476 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001477 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001478 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001479 known.close();
1480 known = null;
1481 if (!tempKnownFile.renameTo(mEverStored)) {
1482 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1483 }
1484 } catch (IOException e) {
1485 // Bad: we couldn't create the new copy. For safety's sake we
1486 // abandon the whole process and remove all what's-backed-up
1487 // state entirely, meaning we'll force a backup pass for every
1488 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001489 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001490 mEverStoredApps.clear();
1491 tempKnownFile.delete();
1492 mEverStored.delete();
1493 } finally {
1494 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001495 }
1496 }
1497 }
1498
Christopher Tateb49ceb32010-02-08 16:22:24 -08001499 // Persistently record the current and ancestral backup tokens as well
1500 // as the set of packages with data [supposedly] available in the
1501 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001502 void writeRestoreTokens() {
1503 try {
1504 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001505
1506 // First, the version number of this record, for futureproofing
1507 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1508
1509 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001510 af.writeLong(mAncestralToken);
1511 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001512
1513 // Now write the set of ancestral packages
1514 if (mAncestralPackages == null) {
1515 af.writeInt(-1);
1516 } else {
1517 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001518 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001519 for (String pkgName : mAncestralPackages) {
1520 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001521 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001522 }
1523 }
Christopher Tate84725812010-02-04 15:52:40 -08001524 af.close();
1525 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001526 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001527 }
1528 }
1529
Dan Egnor87a02bc2009-06-17 02:30:10 -07001530 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001531 private IBackupTransport getTransport(String transportName) {
1532 synchronized (mTransports) {
1533 IBackupTransport transport = mTransports.get(transportName);
1534 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001536 }
1537 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001538 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001539 }
1540
Christopher Tatedf01dea2009-06-09 20:45:02 -07001541 // fire off a backup agent, blocking until it attaches or times out
1542 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1543 IBackupAgent agent = null;
1544 synchronized(mAgentConnectLock) {
1545 mConnecting = true;
1546 mConnectedAgent = null;
1547 try {
1548 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001549 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001550
1551 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001552 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001553 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1554 while (mConnecting && mConnectedAgent == null
1555 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001557 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001558 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001559 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001560 return null;
1561 }
1562 }
1563
1564 // if we timed out with no connect, abort and move on
1565 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001566 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001567 return null;
1568 }
1569 agent = mConnectedAgent;
1570 }
1571 } catch (RemoteException e) {
1572 // can't happen
1573 }
1574 }
1575 return agent;
1576 }
1577
Christopher Tatec7b31e32009-06-10 15:49:30 -07001578 // clear an application's data, blocking until the operation completes or times out
1579 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001580 // Don't wipe packages marked allowClearUserData=false
1581 try {
1582 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1583 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001584 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001585 + packageName);
1586 return;
1587 }
1588 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001590 return;
1591 }
1592
Christopher Tatec7b31e32009-06-10 15:49:30 -07001593 ClearDataObserver observer = new ClearDataObserver();
1594
1595 synchronized(mClearDataLock) {
1596 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001597 try {
1598 mActivityManager.clearApplicationUserData(packageName, observer);
1599 } catch (RemoteException e) {
1600 // can't happen because the activity manager is in this process
1601 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001602
1603 // only wait 10 seconds for the clear data to happen
1604 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1605 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1606 try {
1607 mClearDataLock.wait(5000);
1608 } catch (InterruptedException e) {
1609 // won't happen, but still.
1610 mClearingData = false;
1611 }
1612 }
1613 }
1614 }
1615
1616 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001617 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001618 synchronized(mClearDataLock) {
1619 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001620 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001621 }
1622 }
1623 }
1624
Christopher Tate1bb69062010-02-19 17:02:12 -08001625 // Get the restore-set token for the best-available restore set for this package:
1626 // the active set if possible, else the ancestral one. Returns zero if none available.
1627 long getAvailableRestoreToken(String packageName) {
1628 long token = mAncestralToken;
1629 synchronized (mQueueLock) {
1630 if (mEverStoredApps.contains(packageName)) {
1631 token = mCurrentToken;
1632 }
1633 }
1634 return token;
1635 }
1636
Christopher Tate44a27902010-01-27 17:15:49 -08001637 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001638 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1639
1640 interface BackupRestoreTask {
1641 // Execute one tick of whatever state machine the task implements
1642 void execute();
1643
1644 // An operation that wanted a callback has completed
1645 void operationComplete();
1646
1647 // An operation that wanted a callback has timed out
1648 void handleTimeout();
1649 }
1650
1651 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1652 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1653 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001654 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001655 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1656
1657 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1658 mBackupHandler.sendMessageDelayed(msg, interval);
1659 }
1660 }
1661
1662 // synchronous waiter case
1663 boolean waitUntilOperationComplete(int token) {
1664 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1665 + Integer.toHexString(token));
1666 int finalState = OP_PENDING;
1667 Operation op = null;
1668 synchronized (mCurrentOpLock) {
1669 while (true) {
1670 op = mCurrentOperations.get(token);
1671 if (op == null) {
1672 // mysterious disappearance: treat as success with no callback
1673 break;
1674 } else {
1675 if (op.state == OP_PENDING) {
1676 try {
1677 mCurrentOpLock.wait();
1678 } catch (InterruptedException e) {}
1679 // When the wait is notified we loop around and recheck the current state
1680 } else {
1681 // No longer pending; we're done
1682 finalState = op.state;
1683 break;
1684 }
Christopher Tate44a27902010-01-27 17:15:49 -08001685 }
Christopher Tate44a27902010-01-27 17:15:49 -08001686 }
1687 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001688
Christopher Tate44a27902010-01-27 17:15:49 -08001689 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001690 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001691 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001692 return finalState == OP_ACKNOWLEDGED;
1693 }
1694
Christopher Tate8e294d42011-08-31 20:37:12 -07001695 void handleTimeout(int token, Object obj) {
1696 // Notify any synchronous waiters
1697 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001698 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001699 op = mCurrentOperations.get(token);
1700 if (MORE_DEBUG) {
1701 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1702 + " but no op found");
1703 }
1704 int state = (op != null) ? op.state : OP_TIMEOUT;
1705 if (state == OP_PENDING) {
1706 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1707 op.state = OP_TIMEOUT;
1708 mCurrentOperations.put(token, op);
1709 }
1710 mCurrentOpLock.notifyAll();
1711 }
1712
1713 // If there's a TimeoutHandler for this event, call it
1714 if (op != null && op.callback != null) {
1715 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001716 }
Christopher Tate44a27902010-01-27 17:15:49 -08001717 }
1718
Christopher Tate043dadc2009-06-02 16:11:00 -07001719 // ----- Back up a set of applications via a worker thread -----
1720
Christopher Tate8e294d42011-08-31 20:37:12 -07001721 enum BackupState {
1722 INITIAL,
1723 RUNNING_QUEUE,
1724 FINAL
1725 }
1726
1727 class PerformBackupTask implements BackupRestoreTask {
1728 private static final String TAG = "PerformBackupTask";
1729
Christopher Tateaa088442009-06-16 18:25:46 -07001730 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001731 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001732 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001733 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001734 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001735 BackupState mCurrentState;
1736
1737 // carried information about the current in-flight operation
1738 PackageInfo mCurrentPackage;
1739 File mSavedStateName;
1740 File mBackupDataName;
1741 File mNewStateName;
1742 ParcelFileDescriptor mSavedState;
1743 ParcelFileDescriptor mBackupData;
1744 ParcelFileDescriptor mNewState;
1745 int mStatus;
1746 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001747
Christopher Tate44a27902010-01-27 17:15:49 -08001748 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001749 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001750 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001751 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001752 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001753
1754 try {
1755 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1756 } catch (RemoteException e) {
1757 // can't happen; the transport is local
1758 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001759
1760 mCurrentState = BackupState.INITIAL;
1761 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001762 }
1763
Christopher Tate8e294d42011-08-31 20:37:12 -07001764 // Main entry point: perform one chunk of work, updating the state as appropriate
1765 // and reposting the next chunk to the primary backup handler thread.
1766 @Override
1767 public void execute() {
1768 switch (mCurrentState) {
1769 case INITIAL:
1770 beginBackup();
1771 break;
1772
1773 case RUNNING_QUEUE:
1774 invokeNextAgent();
1775 break;
1776
1777 case FINAL:
1778 if (!mFinished) finalizeBackup();
1779 else {
1780 Slog.e(TAG, "Duplicate finish");
1781 }
Christopher Tate2982d062011-09-06 20:35:24 -07001782 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001783 break;
1784 }
1785 }
1786
1787 // We're starting a backup pass. Initialize the transport and send
1788 // the PM metadata blob if we haven't already.
1789 void beginBackup() {
1790 mStatus = BackupConstants.TRANSPORT_OK;
1791
1792 // Sanity check: if the queue is empty we have no work to do.
1793 if (mOriginalQueue.isEmpty()) {
1794 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1795 return;
1796 }
1797
1798 // We need to retain the original queue contents in case of transport
1799 // failure, but we want a working copy that we can manipulate along
1800 // the way.
1801 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1802
Joe Onorato8a9b2202010-02-26 18:56:32 -08001803 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001804
Christopher Tate8e294d42011-08-31 20:37:12 -07001805 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001806 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001807 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001808
Dan Egnor852f8e42009-09-30 11:20:45 -07001809 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001810 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001811 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001812 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001813 mStatus = mTransport.initializeDevice();
1814 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001815 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001816 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001817 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001818 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001819 }
Dan Egnor01445162009-09-21 17:04:05 -07001820 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001821
1822 // The package manager doesn't have a proper <application> etc, but since
1823 // it's running here in the system process we can just set up its agent
1824 // directly and use a synthetic BackupRequest. We always run this pass
1825 // because it's cheap and this way we guarantee that we don't get out of
1826 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001827 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001828 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1829 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001830 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001831 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1832 }
Christopher Tate90967f42009-09-20 15:28:33 -07001833
Christopher Tate8e294d42011-08-31 20:37:12 -07001834 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1835 // The backend reports that our dataset has been wiped. Note this in
1836 // the event log; the no-success code below will reset the backup
1837 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001838 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001839 }
1840 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001842 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001843 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001844 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1845 // metadata and its completion/timeout callback will continue the state
1846 // machine chain. If it failed that won't happen; we handle that now.
1847 if (mStatus != BackupConstants.TRANSPORT_OK) {
1848 // if things went wrong at this point, we need to
1849 // restage everything and try again later.
1850 resetBackupState(mStateDir); // Just to make sure.
1851 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001852 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001853 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001854 }
1855
Christopher Tate8e294d42011-08-31 20:37:12 -07001856 // Transport has been initialized and the PM metadata submitted successfully
1857 // if that was warranted. Now we process the single next thing in the queue.
1858 void invokeNextAgent() {
1859 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001860
Christopher Tate8e294d42011-08-31 20:37:12 -07001861 // Sanity check that we have work to do. If not, skip to the end where
1862 // we reestablish the wakelock invariants etc.
1863 if (mQueue.isEmpty()) {
1864 Slog.e(TAG, "Running queue but it's empty!");
1865 executeNextState(BackupState.FINAL);
1866 return;
1867 }
1868
1869 // pop the entry we're going to process on this step
1870 BackupRequest request = mQueue.get(0);
1871 mQueue.remove(0);
1872
1873 Slog.d(TAG, "starting agent for backup of " + request);
1874
1875 // Verify that the requested app exists; it might be something that
1876 // requested a backup but was then uninstalled. The request was
1877 // journalled and rather than tamper with the journal it's safer
1878 // to sanity-check here. This also gives us the classname of the
1879 // package's backup agent.
1880 try {
1881 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1882 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001883
Christopher Tate043dadc2009-06-02 16:11:00 -07001884 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001885 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001886 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1887 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001888 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001889 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001890 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1891 // at this point we'll either get a completion callback from the
1892 // agent, or a timeout message on the main handler. either way, we're
1893 // done here as long as we're successful so far.
1894 } else {
1895 // Timeout waiting for the agent
1896 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001897 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001898 } catch (SecurityException ex) {
1899 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001901 mStatus = BackupConstants.AGENT_ERROR;
1902 }
1903 } catch (NameNotFoundException e) {
1904 Slog.d(TAG, "Package does not exist; skipping");
1905 } finally {
1906 mWakelock.setWorkSource(null);
1907
1908 // If there was an agent error, no timeout/completion handling will occur.
1909 // That means we need to deal with the next state ourselves.
1910 if (mStatus != BackupConstants.TRANSPORT_OK) {
1911 BackupState nextState = BackupState.RUNNING_QUEUE;
1912
1913 // An agent-level failure means we reenqueue this one agent for
1914 // a later retry, but otherwise proceed normally.
1915 if (mStatus == BackupConstants.AGENT_ERROR) {
1916 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1917 + " - restaging");
1918 dataChangedImpl(request.packageName);
1919 mStatus = BackupConstants.TRANSPORT_OK;
1920 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1921 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1922 // Transport-level failure means we reenqueue everything
1923 revertAndEndBackup();
1924 nextState = BackupState.FINAL;
1925 }
1926
1927 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001928 }
1929 }
1930 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001931
Christopher Tate8e294d42011-08-31 20:37:12 -07001932 void finalizeBackup() {
1933 // Either backup was successful, in which case we of course do not need
1934 // this pass's journal any more; or it failed, in which case we just
1935 // re-enqueued all of these packages in the current active journal.
1936 // Either way, we no longer need this pass's journal.
1937 if (mJournal != null && !mJournal.delete()) {
1938 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1939 }
1940
1941 // If everything actually went through and this is the first time we've
1942 // done a backup, we can now record what the current backup dataset token
1943 // is.
1944 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1945 try {
1946 mCurrentToken = mTransport.getCurrentRestoreSet();
1947 } catch (RemoteException e) {} // can't happen
1948 writeRestoreTokens();
1949 }
1950
1951 // Set up the next backup pass
1952 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1953 backupNow();
1954 }
1955
1956 // Only once we're entirely finished do we release the wakelock
1957 Slog.i(TAG, "Backup pass finished.");
1958 mWakelock.release();
1959 }
1960
1961 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1962 // handler in case it doesn't get back to us.
1963 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001964 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001965 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001966
Christopher Tate8e294d42011-08-31 20:37:12 -07001967 mSavedStateName = new File(mStateDir, packageName);
1968 mBackupDataName = new File(mDataDir, packageName + ".data");
1969 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001970
Christopher Tate8e294d42011-08-31 20:37:12 -07001971 mSavedState = null;
1972 mBackupData = null;
1973 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001974
Christopher Tate4a627c72011-04-01 14:43:32 -07001975 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001976 try {
1977 // Look up the package info & signatures. This is first so that if it
1978 // throws an exception, there's no file setup yet that would need to
1979 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001980 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001981 // The metadata 'package' is synthetic; construct one and make
1982 // sure our global state is pointed at it
1983 mCurrentPackage = new PackageInfo();
1984 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07001985 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001986
Christopher Tatec7b31e32009-06-10 15:49:30 -07001987 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001988 // the saved-state "file". This is by definition an incremental,
1989 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07001990 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07001991 ParcelFileDescriptor.MODE_READ_ONLY |
1992 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001993
Christopher Tate8e294d42011-08-31 20:37:12 -07001994 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001995 ParcelFileDescriptor.MODE_READ_WRITE |
1996 ParcelFileDescriptor.MODE_CREATE |
1997 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001998
Christopher Tate8e294d42011-08-31 20:37:12 -07001999 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002000 ParcelFileDescriptor.MODE_READ_WRITE |
2001 ParcelFileDescriptor.MODE_CREATE |
2002 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002003
Christopher Tate44a27902010-01-27 17:15:49 -08002004 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07002005 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2006 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002007 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002008 Slog.e(TAG, "Error invoking for backup on " + packageName);
2009 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2010 e.toString());
2011 agentErrorCleanup();
2012 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002013 }
2014
Christopher Tate8e294d42011-08-31 20:37:12 -07002015 // At this point the agent is off and running. The next thing to happen will
2016 // either be a callback from the agent, at which point we'll process its data
2017 // for transport, or a timeout. Either way the next phase will happen in
2018 // response to the TimeoutHandler interface callbacks.
2019 return BackupConstants.TRANSPORT_OK;
2020 }
2021
2022 @Override
2023 public void operationComplete() {
2024 // Okay, the agent successfully reported back to us. Spin the data off to the
2025 // transport and proceed with the next stage.
2026 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2027 + mCurrentPackage.packageName);
2028 mBackupHandler.removeMessages(MSG_TIMEOUT);
2029 clearAgentState();
2030
2031 ParcelFileDescriptor backupData = null;
2032 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002033 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002035 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002036 if (mStatus == BackupConstants.TRANSPORT_OK) {
2037 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002038 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002039 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002040 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002041
Dan Egnor83861e72009-09-17 16:17:55 -07002042 // TODO - We call finishBackup() for each application backed up, because
2043 // we need to know now whether it succeeded or failed. Instead, we should
2044 // hold off on finishBackup() until the end, which implies holding off on
2045 // renaming *all* the output state files (see below) until that happens.
2046
Christopher Tate8e294d42011-08-31 20:37:12 -07002047 if (mStatus == BackupConstants.TRANSPORT_OK) {
2048 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002049 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002050 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002051 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002052 }
2053
2054 // After successful transport, delete the now-stale data
2055 // and juggle the files so that next time we supply the agent
2056 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002057 if (mStatus == BackupConstants.TRANSPORT_OK) {
2058 mBackupDataName.delete();
2059 mNewStateName.renameTo(mSavedStateName);
2060 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2061 mCurrentPackage.packageName, size);
2062 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002063 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002064 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2065 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002066 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002067 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002068 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2069 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2070 mCurrentPackage.packageName);
2071 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002072 } finally {
2073 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002074 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002075
Christopher Tate8e294d42011-08-31 20:37:12 -07002076 // If we encountered an error here it's a transport-level failure. That
2077 // means we need to halt everything and reschedule everything for next time.
2078 final BackupState nextState;
2079 if (mStatus != BackupConstants.TRANSPORT_OK) {
2080 revertAndEndBackup();
2081 nextState = BackupState.FINAL;
2082 } else {
2083 // Success! Proceed with the next app if any, otherwise we're done.
2084 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2085 }
2086
2087 executeNextState(nextState);
2088 }
2089
2090 @Override
2091 public void handleTimeout() {
2092 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2093 // it for the next time we run a backup pass.
2094 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2095 // fail repeatedly (i.e. have proved themselves to be buggy).
2096 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2097 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2098 "timeout");
2099 agentErrorCleanup();
2100 dataChangedImpl(mCurrentPackage.packageName);
2101 }
2102
2103 void revertAndEndBackup() {
2104 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2105 for (BackupRequest request : mOriginalQueue) {
2106 dataChangedImpl(request.packageName);
2107 }
2108 // We also want to reset the backup schedule based on whatever
2109 // the transport suggests by way of retry/backoff time.
2110 restartBackupAlarm();
2111 }
2112
2113 void agentErrorCleanup() {
2114 mBackupDataName.delete();
2115 mNewStateName.delete();
2116 clearAgentState();
2117
2118 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2119 }
2120
2121 // Cleanup common to both success and failure cases
2122 void clearAgentState() {
2123 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2124 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2125 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2126 mSavedState = mBackupData = mNewState = null;
2127 synchronized (mCurrentOpLock) {
2128 mCurrentOperations.clear();
2129 }
2130
2131 // If this was a pseudopackage there's no associated Activity Manager state
2132 if (mCurrentPackage.applicationInfo != null) {
2133 try { // unbind even on timeout, just in case
2134 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2135 } catch (RemoteException e) {}
2136 }
2137 }
2138
2139 void restartBackupAlarm() {
2140 synchronized (mQueueLock) {
2141 try {
2142 startBackupAlarmsLocked(mTransport.requestBackupTime());
2143 } catch (RemoteException e) { /* cannot happen */ }
2144 }
2145 }
2146
2147 void executeNextState(BackupState nextState) {
2148 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2149 + this + " nextState=" + nextState);
2150 mCurrentState = nextState;
2151 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2152 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002153 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002154 }
2155
Christopher Tatedf01dea2009-06-09 20:45:02 -07002156
Christopher Tate4a627c72011-04-01 14:43:32 -07002157 // ----- Full backup to a file/socket -----
2158
2159 class PerformFullBackupTask implements Runnable {
2160 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002161 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002162 IFullBackupRestoreObserver mObserver;
2163 boolean mIncludeApks;
2164 boolean mIncludeShared;
2165 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002166 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002167 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002168 String mCurrentPassword;
2169 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002170 AtomicBoolean mLatchObject;
2171 File mFilesDir;
2172 File mManifestFile;
2173
Christopher Tate7926a692011-07-11 11:31:57 -07002174 class FullBackupRunner implements Runnable {
2175 PackageInfo mPackage;
2176 IBackupAgent mAgent;
2177 ParcelFileDescriptor mPipe;
2178 int mToken;
2179 boolean mSendApk;
2180
2181 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2182 int token, boolean sendApk) throws IOException {
2183 mPackage = pack;
2184 mAgent = agent;
2185 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2186 mToken = token;
2187 mSendApk = sendApk;
2188 }
2189
2190 @Override
2191 public void run() {
2192 try {
2193 BackupDataOutput output = new BackupDataOutput(
2194 mPipe.getFileDescriptor());
2195
Christopher Tatec58efa62011-08-01 19:20:14 -07002196 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002197 writeAppManifest(mPackage, mManifestFile, mSendApk);
2198 FullBackup.backupToTar(mPackage.packageName, null, null,
2199 mFilesDir.getAbsolutePath(),
2200 mManifestFile.getAbsolutePath(),
2201 output);
2202
2203 if (mSendApk) {
2204 writeApkToBackup(mPackage, output);
2205 }
2206
Christopher Tatec58efa62011-08-01 19:20:14 -07002207 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002208 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002209 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2210 } catch (IOException e) {
2211 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2212 } catch (RemoteException e) {
2213 Slog.e(TAG, "Remote agent vanished during full backup of "
2214 + mPackage.packageName);
2215 } finally {
2216 try {
2217 mPipe.close();
2218 } catch (IOException e) {}
2219 }
2220 }
2221 }
2222
Christopher Tate4a627c72011-04-01 14:43:32 -07002223 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002224 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002225 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002226 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002227 mOutputFile = fd;
2228 mObserver = observer;
2229 mIncludeApks = includeApks;
2230 mIncludeShared = includeShared;
2231 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002232 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002233 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002234 mCurrentPassword = curPassword;
2235 // when backing up, if there is a current backup password, we require that
2236 // the user use a nonempty encryption password as well. if one is supplied
2237 // in the UI we use that, but if the UI was left empty we fall back to the
2238 // current backup password (which was supplied by the user as well).
2239 if (encryptPassword == null || "".equals(encryptPassword)) {
2240 mEncryptPassword = curPassword;
2241 } else {
2242 mEncryptPassword = encryptPassword;
2243 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002244 mLatchObject = latch;
2245
2246 mFilesDir = new File("/data/system");
2247 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2248 }
2249
2250 @Override
2251 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002252 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002253
Christopher Tateb0628bf2011-06-02 15:08:13 -07002254 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002255 sendStartBackup();
2256
2257 // doAllApps supersedes the package set if any
2258 if (mAllApps) {
2259 packagesToBackup = mPackageManager.getInstalledPackages(
2260 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002261 // Exclude system apps if we've been asked to do so
2262 if (mIncludeSystem == false) {
2263 for (int i = 0; i < packagesToBackup.size(); ) {
2264 PackageInfo pkg = packagesToBackup.get(i);
2265 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2266 packagesToBackup.remove(i);
2267 } else {
2268 i++;
2269 }
2270 }
2271 }
2272 }
2273
2274 // Now process the command line argument packages, if any. Note that explicitly-
2275 // named system-partition packages will be included even if includeSystem was
2276 // set to false.
2277 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002278 for (String pkgName : mPackages) {
2279 try {
2280 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2281 PackageManager.GET_SIGNATURES));
2282 } catch (NameNotFoundException e) {
2283 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2284 }
2285 }
2286 }
2287
Christopher Tatea858cb02011-06-03 12:27:51 -07002288 // Cull any packages that have indicated that backups are not permitted.
2289 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002290 PackageInfo pkg = packagesToBackup.get(i);
2291 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002292 packagesToBackup.remove(i);
2293 } else {
2294 i++;
2295 }
2296 }
2297
Christopher Tate7926a692011-07-11 11:31:57 -07002298 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002299 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002300
Christopher Tate4a627c72011-04-01 14:43:32 -07002301 PackageInfo pkg = null;
2302 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002303 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002304 boolean compressing = COMPRESS_FULL_BACKUPS;
2305 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002306
Christopher Tateeef4ae42011-08-05 13:15:53 -07002307 // Verify that the given password matches the currently-active
2308 // backup password, if any
2309 if (hasBackupPassword()) {
2310 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2311 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2312 return;
2313 }
2314 }
2315
Christopher Tate7bdb0962011-07-13 19:30:21 -07002316 // Write the global file header. All strings are UTF-8 encoded; lines end
2317 // with a '\n' byte. Actual backup data begins immediately following the
2318 // final '\n'.
2319 //
2320 // line 1: "ANDROID BACKUP"
2321 // line 2: backup file format version, currently "1"
2322 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002323 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2324 //
2325 // When line 4 is not "none", then additional header data follows:
2326 //
2327 // line 5: user password salt [hex]
2328 // line 6: master key checksum salt [hex]
2329 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2330 // line 8: IV of the user key [hex]
2331 // line 9: master key blob [hex]
2332 // IV of the master key, master key itself, master key checksum hash
2333 //
2334 // The master key checksum is the master key plus its checksum salt, run through
2335 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2336 // correct password for decrypting the archive: the master key decrypted from
2337 // the archive using the user-supplied password is also run through PBKDF2 in
2338 // this way, and if the result does not match the checksum as stored in the
2339 // archive, then we know that the user-supplied password does not match the
2340 // archive's.
2341 StringBuilder headerbuf = new StringBuilder(1024);
2342
Christopher Tate7bdb0962011-07-13 19:30:21 -07002343 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002344 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2345 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002346
2347 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002348 // Set up the encryption stage if appropriate, and emit the correct header
2349 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002350 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2351 } else {
2352 headerbuf.append("none\n");
2353 }
2354
Christopher Tate7bdb0962011-07-13 19:30:21 -07002355 byte[] header = headerbuf.toString().getBytes("UTF-8");
2356 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002357
2358 // Set up the compression stage feeding into the encryption stage (if any)
2359 if (compressing) {
2360 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2361 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2362 }
2363
2364 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002365 } catch (Exception e) {
2366 // Should never happen!
2367 Slog.e(TAG, "Unable to emit archive header", e);
2368 return;
2369 }
2370
Christopher Tateb0628bf2011-06-02 15:08:13 -07002371 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002372 int N = packagesToBackup.size();
2373 for (int i = 0; i < N; i++) {
2374 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002375 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002376 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002377
Christopher Tate6853fcf2011-08-10 17:52:21 -07002378 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002379 if (mIncludeShared) {
2380 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002381 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002382
2383 // Done!
2384 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002385 } catch (RemoteException e) {
2386 Slog.e(TAG, "App died during full backup");
2387 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002388 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002389 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002390 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002391 mOutputFile.close();
2392 } catch (IOException e) {
2393 /* nothing we can do about this */
2394 }
2395 synchronized (mCurrentOpLock) {
2396 mCurrentOperations.clear();
2397 }
2398 synchronized (mLatchObject) {
2399 mLatchObject.set(true);
2400 mLatchObject.notifyAll();
2401 }
2402 sendEndBackup();
2403 mWakelock.release();
2404 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2405 }
2406 }
2407
Christopher Tate2efd2db2011-07-19 16:32:49 -07002408 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2409 OutputStream ofstream) throws Exception {
2410 // User key will be used to encrypt the master key.
2411 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002412 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002413 PBKDF2_HASH_ROUNDS);
2414
2415 // the master key is random for each backup
2416 byte[] masterPw = new byte[256 / 8];
2417 mRng.nextBytes(masterPw);
2418 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2419
2420 // primary encryption of the datastream with the random key
2421 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2422 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2423 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2424 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2425
2426 // line 4: name of encryption algorithm
2427 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2428 headerbuf.append('\n');
2429 // line 5: user password salt [hex]
2430 headerbuf.append(byteArrayToHex(newUserSalt));
2431 headerbuf.append('\n');
2432 // line 6: master key checksum salt [hex]
2433 headerbuf.append(byteArrayToHex(checksumSalt));
2434 headerbuf.append('\n');
2435 // line 7: number of PBKDF2 rounds used [decimal]
2436 headerbuf.append(PBKDF2_HASH_ROUNDS);
2437 headerbuf.append('\n');
2438
2439 // line 8: IV of the user key [hex]
2440 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2441 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2442
2443 byte[] IV = mkC.getIV();
2444 headerbuf.append(byteArrayToHex(IV));
2445 headerbuf.append('\n');
2446
2447 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2448 // [byte] IV length = Niv
2449 // [array of Niv bytes] IV itself
2450 // [byte] master key length = Nmk
2451 // [array of Nmk bytes] master key itself
2452 // [byte] MK checksum hash length = Nck
2453 // [array of Nck bytes] master key checksum hash
2454 //
2455 // The checksum is the (master key + checksum salt), run through the
2456 // stated number of PBKDF2 rounds
2457 IV = c.getIV();
2458 byte[] mk = masterKeySpec.getEncoded();
2459 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2460 checksumSalt, PBKDF2_HASH_ROUNDS);
2461
2462 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2463 + checksum.length + 3);
2464 DataOutputStream mkOut = new DataOutputStream(blob);
2465 mkOut.writeByte(IV.length);
2466 mkOut.write(IV);
2467 mkOut.writeByte(mk.length);
2468 mkOut.write(mk);
2469 mkOut.writeByte(checksum.length);
2470 mkOut.write(checksum);
2471 mkOut.flush();
2472 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2473 headerbuf.append(byteArrayToHex(encryptedMk));
2474 headerbuf.append('\n');
2475
2476 return finalOutput;
2477 }
2478
2479 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002480 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002481 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2482
2483 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2484 IApplicationThread.BACKUP_MODE_FULL);
2485 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002486 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002487 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002488 pipes = ParcelFileDescriptor.createPipe();
2489
Christopher Tateb0628bf2011-06-02 15:08:13 -07002490 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002491 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002492 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2493 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2494 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2495
2496 sendOnBackupPackage(pkg.packageName);
2497
Christopher Tate7926a692011-07-11 11:31:57 -07002498 final int token = generateToken();
2499 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2500 token, sendApk);
2501 pipes[1].close(); // the runner has dup'd it
2502 pipes[1] = null;
2503 Thread t = new Thread(runner);
2504 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002505
Christopher Tate7926a692011-07-11 11:31:57 -07002506 // Now pull data from the app and stuff it into the compressor
2507 try {
2508 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2509 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002510
Christopher Tate7926a692011-07-11 11:31:57 -07002511 byte[] buffer = new byte[16 * 1024];
2512 int chunkTotal;
2513 while ((chunkTotal = in.readInt()) > 0) {
2514 while (chunkTotal > 0) {
2515 int toRead = (chunkTotal > buffer.length)
2516 ? buffer.length : chunkTotal;
2517 int nRead = in.read(buffer, 0, toRead);
2518 out.write(buffer, 0, nRead);
2519 chunkTotal -= nRead;
2520 }
2521 }
2522 } catch (IOException e) {
2523 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002524 }
2525
Christopher Tateb0628bf2011-06-02 15:08:13 -07002526 if (!waitUntilOperationComplete(token)) {
2527 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2528 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002529 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002530 }
Christopher Tate7926a692011-07-11 11:31:57 -07002531
Christopher Tateb0628bf2011-06-02 15:08:13 -07002532 } catch (IOException e) {
2533 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002534 } finally {
2535 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002536 // flush after every package
2537 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002538 if (pipes != null) {
2539 if (pipes[0] != null) pipes[0].close();
2540 if (pipes[1] != null) pipes[1].close();
2541 }
Christopher Tate7926a692011-07-11 11:31:57 -07002542 } catch (IOException e) {
2543 Slog.w(TAG, "Error bringing down backup stack");
2544 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002545 }
2546 } else {
2547 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2548 }
2549 tearDown(pkg);
2550 }
2551
Christopher Tate79ec80d2011-06-24 14:58:49 -07002552 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2553 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2554 final String appSourceDir = pkg.applicationInfo.sourceDir;
2555 final String apkDir = new File(appSourceDir).getParent();
2556 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2557 apkDir, appSourceDir, output);
2558
2559 // Save associated .obb content if it exists and we did save the apk
2560 // check for .obb and save those too
2561 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2562 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002563 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002564 File[] obbFiles = obbDir.listFiles();
2565 if (obbFiles != null) {
2566 final String obbDirName = obbDir.getAbsolutePath();
2567 for (File obb : obbFiles) {
2568 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2569 obbDirName, obb.getAbsolutePath(), output);
2570 }
2571 }
2572 }
2573 }
2574
Christopher Tateb0628bf2011-06-02 15:08:13 -07002575 private void backupSharedStorage() throws RemoteException {
2576 PackageInfo pkg = null;
2577 try {
2578 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2579 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2580 IApplicationThread.BACKUP_MODE_FULL);
2581 if (agent != null) {
2582 sendOnBackupPackage("Shared storage");
2583
2584 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002585 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002586 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002587 if (!waitUntilOperationComplete(token)) {
2588 Slog.e(TAG, "Full backup failed on shared storage");
2589 } else {
2590 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2591 }
2592 } else {
2593 Slog.e(TAG, "Could not bind to shared storage backup agent");
2594 }
2595 } catch (NameNotFoundException e) {
2596 Slog.e(TAG, "Shared storage backup package not found");
2597 } finally {
2598 tearDown(pkg);
2599 }
2600 }
2601
Christopher Tate6853fcf2011-08-10 17:52:21 -07002602 private void finalizeBackup(OutputStream out) {
2603 try {
2604 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2605 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2606 out.write(eof);
2607 } catch (IOException e) {
2608 Slog.w(TAG, "Error attempting to finalize backup stream");
2609 }
2610 }
2611
Christopher Tate4a627c72011-04-01 14:43:32 -07002612 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2613 throws IOException {
2614 // Manifest format. All data are strings ending in LF:
2615 // BACKUP_MANIFEST_VERSION, currently 1
2616 //
2617 // Version 1:
2618 // package name
2619 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002620 // platform versionCode
2621 // getInstallerPackageName() for this package (maybe empty)
2622 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002623 // number of signatures == N
2624 // N*: signature byte array in ascii format per Signature.toCharsString()
2625 StringBuilder builder = new StringBuilder(4096);
2626 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2627
2628 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2629 printer.println(pkg.packageName);
2630 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002631 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2632
2633 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2634 printer.println((installerName != null) ? installerName : "");
2635
Christopher Tate4a627c72011-04-01 14:43:32 -07002636 printer.println(withApk ? "1" : "0");
2637 if (pkg.signatures == null) {
2638 printer.println("0");
2639 } else {
2640 printer.println(Integer.toString(pkg.signatures.length));
2641 for (Signature sig : pkg.signatures) {
2642 printer.println(sig.toCharsString());
2643 }
2644 }
2645
2646 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002647 outstream.write(builder.toString().getBytes());
2648 outstream.close();
2649 }
2650
2651 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002652 if (pkg != null) {
2653 final ApplicationInfo app = pkg.applicationInfo;
2654 if (app != null) {
2655 try {
2656 // unbind and tidy up even on timeout or failure, just in case
2657 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002658
Christopher Tateb0628bf2011-06-02 15:08:13 -07002659 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002660 if (app.uid != Process.SYSTEM_UID
2661 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002662 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002663 mActivityManager.killApplicationProcess(app.processName, app.uid);
2664 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002665 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002666 }
2667 } catch (RemoteException e) {
2668 Slog.d(TAG, "Lost app trying to shut down");
2669 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002670 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002671 }
2672 }
2673
2674 // wrappers for observer use
2675 void sendStartBackup() {
2676 if (mObserver != null) {
2677 try {
2678 mObserver.onStartBackup();
2679 } catch (RemoteException e) {
2680 Slog.w(TAG, "full backup observer went away: startBackup");
2681 mObserver = null;
2682 }
2683 }
2684 }
2685
2686 void sendOnBackupPackage(String name) {
2687 if (mObserver != null) {
2688 try {
2689 // TODO: use a more user-friendly name string
2690 mObserver.onBackupPackage(name);
2691 } catch (RemoteException e) {
2692 Slog.w(TAG, "full backup observer went away: backupPackage");
2693 mObserver = null;
2694 }
2695 }
2696 }
2697
2698 void sendEndBackup() {
2699 if (mObserver != null) {
2700 try {
2701 mObserver.onEndBackup();
2702 } catch (RemoteException e) {
2703 Slog.w(TAG, "full backup observer went away: endBackup");
2704 mObserver = null;
2705 }
2706 }
2707 }
2708 }
2709
2710
Christopher Tate75a99702011-05-18 16:28:19 -07002711 // ----- Full restore from a file/socket -----
2712
2713 // Description of a file in the restore datastream
2714 static class FileMetadata {
2715 String packageName; // name of the owning app
2716 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002717 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002718 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2719 String path; // subpath within the semantic domain
2720 long mode; // e.g. 0666 (actually int)
2721 long mtime; // last mod time, UTC time_t (actually int)
2722 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002723
2724 @Override
2725 public String toString() {
2726 StringBuilder sb = new StringBuilder(128);
2727 sb.append("FileMetadata{");
2728 sb.append(packageName); sb.append(',');
2729 sb.append(type); sb.append(',');
2730 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2731 sb.append(size);
2732 sb.append('}');
2733 return sb.toString();
2734 }
Christopher Tate75a99702011-05-18 16:28:19 -07002735 }
2736
2737 enum RestorePolicy {
2738 IGNORE,
2739 ACCEPT,
2740 ACCEPT_IF_APK
2741 }
2742
2743 class PerformFullRestoreTask implements Runnable {
2744 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002745 String mCurrentPassword;
2746 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002747 IFullBackupRestoreObserver mObserver;
2748 AtomicBoolean mLatchObject;
2749 IBackupAgent mAgent;
2750 String mAgentPackage;
2751 ApplicationInfo mTargetApp;
2752 ParcelFileDescriptor[] mPipes = null;
2753
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002754 long mBytes;
2755
Christopher Tate75a99702011-05-18 16:28:19 -07002756 // possible handling states for a given package in the restore dataset
2757 final HashMap<String, RestorePolicy> mPackagePolicies
2758 = new HashMap<String, RestorePolicy>();
2759
2760 // installer package names for each encountered app, derived from the manifests
2761 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2762
2763 // Signatures for a given package found in its manifest file
2764 final HashMap<String, Signature[]> mManifestSignatures
2765 = new HashMap<String, Signature[]>();
2766
2767 // Packages we've already wiped data on when restoring their first file
2768 final HashSet<String> mClearedPackages = new HashSet<String>();
2769
Christopher Tate728a1c42011-07-28 18:03:03 -07002770 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002771 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002772 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002773 mCurrentPassword = curPassword;
2774 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002775 mObserver = observer;
2776 mLatchObject = latch;
2777 mAgent = null;
2778 mAgentPackage = null;
2779 mTargetApp = null;
2780
2781 // Which packages we've already wiped data on. We prepopulate this
2782 // with a whitelist of packages known to be unclearable.
2783 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002784 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002785
Christopher Tate75a99702011-05-18 16:28:19 -07002786 }
2787
2788 class RestoreFileRunnable implements Runnable {
2789 IBackupAgent mAgent;
2790 FileMetadata mInfo;
2791 ParcelFileDescriptor mSocket;
2792 int mToken;
2793
2794 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2795 ParcelFileDescriptor socket, int token) throws IOException {
2796 mAgent = agent;
2797 mInfo = info;
2798 mToken = token;
2799
2800 // This class is used strictly for process-local binder invocations. The
2801 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2802 // do not automatically get a 'dup'ed descriptor that we can can continue
2803 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2804 // before proceeding to do the restore.
2805 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2806 }
2807
2808 @Override
2809 public void run() {
2810 try {
2811 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2812 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2813 mToken, mBackupManagerBinder);
2814 } catch (RemoteException e) {
2815 // never happens; this is used strictly for local binder calls
2816 }
2817 }
2818 }
2819
2820 @Override
2821 public void run() {
2822 Slog.i(TAG, "--- Performing full-dataset restore ---");
2823 sendStartRestore();
2824
Christopher Tateb0628bf2011-06-02 15:08:13 -07002825 // Are we able to restore shared-storage data?
2826 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2827 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2828 }
2829
Christopher Tate2efd2db2011-07-19 16:32:49 -07002830 FileInputStream rawInStream = null;
2831 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002832 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002833 if (hasBackupPassword()) {
2834 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2835 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2836 return;
2837 }
2838 }
2839
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002840 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002841 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002842 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2843 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002844
2845 // First, parse out the unencrypted/uncompressed header
2846 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002847 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002848 final InputStream in;
2849
2850 boolean okay = false;
2851 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2852 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002853 rawDataIn.readFully(streamHeader);
2854 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2855 if (Arrays.equals(magicBytes, streamHeader)) {
2856 // okay, header looks good. now parse out the rest of the fields.
2857 String s = readHeaderLine(rawInStream);
2858 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2859 // okay, it's a version we recognize
2860 s = readHeaderLine(rawInStream);
2861 compressed = (Integer.parseInt(s) != 0);
2862 s = readHeaderLine(rawInStream);
2863 if (s.equals("none")) {
2864 // no more header to parse; we're good to go
2865 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002866 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002867 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2868 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002869 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002870 }
2871 } else Slog.w(TAG, "Archive is encrypted but no password given");
2872 } else Slog.w(TAG, "Wrong header version: " + s);
2873 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002874
2875 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002876 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002877 return;
2878 }
2879
2880 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002881 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002882
2883 boolean didRestore;
2884 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002885 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002886 } while (didRestore);
2887
Christopher Tatec58efa62011-08-01 19:20:14 -07002888 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002889 } catch (IOException e) {
2890 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002891 } finally {
2892 tearDownPipes();
2893 tearDownAgent(mTargetApp);
2894
2895 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002896 if (rawDataIn != null) rawDataIn.close();
2897 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002898 mInputFile.close();
2899 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002900 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002901 /* nothing we can do about this */
2902 }
2903 synchronized (mCurrentOpLock) {
2904 mCurrentOperations.clear();
2905 }
2906 synchronized (mLatchObject) {
2907 mLatchObject.set(true);
2908 mLatchObject.notifyAll();
2909 }
2910 sendEndRestore();
2911 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002912 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002913 }
2914 }
2915
Christopher Tate7bdb0962011-07-13 19:30:21 -07002916 String readHeaderLine(InputStream in) throws IOException {
2917 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002918 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002919 while ((c = in.read()) >= 0) {
2920 if (c == '\n') break; // consume and discard the newlines
2921 buffer.append((char)c);
2922 }
2923 return buffer.toString();
2924 }
2925
Christopher Tate2efd2db2011-07-19 16:32:49 -07002926 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2927 InputStream result = null;
2928 try {
2929 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2930
2931 String userSaltHex = readHeaderLine(rawInStream); // 5
2932 byte[] userSalt = hexToByteArray(userSaltHex);
2933
2934 String ckSaltHex = readHeaderLine(rawInStream); // 6
2935 byte[] ckSalt = hexToByteArray(ckSaltHex);
2936
2937 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2938 String userIvHex = readHeaderLine(rawInStream); // 8
2939
2940 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2941
2942 // decrypt the master key blob
2943 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002944 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002945 rounds);
2946 byte[] IV = hexToByteArray(userIvHex);
2947 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2948 c.init(Cipher.DECRYPT_MODE,
2949 new SecretKeySpec(userKey.getEncoded(), "AES"),
2950 ivSpec);
2951 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2952 byte[] mkBlob = c.doFinal(mkCipher);
2953
2954 // first, the master key IV
2955 int offset = 0;
2956 int len = mkBlob[offset++];
2957 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2958 offset += len;
2959 // then the master key itself
2960 len = mkBlob[offset++];
2961 byte[] mk = Arrays.copyOfRange(mkBlob,
2962 offset, offset + len);
2963 offset += len;
2964 // and finally the master key checksum hash
2965 len = mkBlob[offset++];
2966 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2967 offset, offset + len);
2968
2969 // now validate the decrypted master key against the checksum
2970 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2971 if (Arrays.equals(calculatedCk, mkChecksum)) {
2972 ivSpec = new IvParameterSpec(IV);
2973 c.init(Cipher.DECRYPT_MODE,
2974 new SecretKeySpec(mk, "AES"),
2975 ivSpec);
2976 // Only if all of the above worked properly will 'result' be assigned
2977 result = new CipherInputStream(rawInStream, c);
2978 } else Slog.w(TAG, "Incorrect password");
2979 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2980 } catch (InvalidAlgorithmParameterException e) {
2981 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2982 } catch (BadPaddingException e) {
2983 // This case frequently occurs when the wrong password is used to decrypt
2984 // the master key. Use the identical "incorrect password" log text as is
2985 // used in the checksum failure log in order to avoid providing additional
2986 // information to an attacker.
2987 Slog.w(TAG, "Incorrect password");
2988 } catch (IllegalBlockSizeException e) {
2989 Slog.w(TAG, "Invalid block size in master key");
2990 } catch (NoSuchAlgorithmException e) {
2991 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2992 } catch (NoSuchPaddingException e) {
2993 Slog.e(TAG, "Needed padding mechanism unavailable!");
2994 } catch (InvalidKeyException e) {
2995 Slog.w(TAG, "Illegal password; aborting");
2996 } catch (NumberFormatException e) {
2997 Slog.w(TAG, "Can't parse restore data header");
2998 } catch (IOException e) {
2999 Slog.w(TAG, "Can't read input header");
3000 }
3001
3002 return result;
3003 }
3004
Christopher Tate75a99702011-05-18 16:28:19 -07003005 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3006 FileMetadata info;
3007 try {
3008 info = readTarHeaders(instream);
3009 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003010 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003011 dumpFileMetadata(info);
3012 }
3013
3014 final String pkg = info.packageName;
3015 if (!pkg.equals(mAgentPackage)) {
3016 // okay, change in package; set up our various
3017 // bookkeeping if we haven't seen it yet
3018 if (!mPackagePolicies.containsKey(pkg)) {
3019 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3020 }
3021
3022 // Clean up the previous agent relationship if necessary,
3023 // and let the observer know we're considering a new app.
3024 if (mAgent != null) {
3025 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3026 tearDownPipes();
3027 tearDownAgent(mTargetApp);
3028 mTargetApp = null;
3029 mAgentPackage = null;
3030 }
3031 }
3032
3033 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3034 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3035 mPackageInstallers.put(pkg, info.installerPackageName);
3036 // We've read only the manifest content itself at this point,
3037 // so consume the footer before looping around to the next
3038 // input file
3039 skipTarPadding(info.size, instream);
3040 sendOnRestorePackage(pkg);
3041 } else {
3042 // Non-manifest, so it's actual file data. Is this a package
3043 // we're ignoring?
3044 boolean okay = true;
3045 RestorePolicy policy = mPackagePolicies.get(pkg);
3046 switch (policy) {
3047 case IGNORE:
3048 okay = false;
3049 break;
3050
3051 case ACCEPT_IF_APK:
3052 // If we're in accept-if-apk state, then the first file we
3053 // see MUST be the apk.
3054 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3055 if (DEBUG) Slog.d(TAG, "APK file; installing");
3056 // Try to install the app.
3057 String installerName = mPackageInstallers.get(pkg);
3058 okay = installApk(info, installerName, instream);
3059 // good to go; promote to ACCEPT
3060 mPackagePolicies.put(pkg, (okay)
3061 ? RestorePolicy.ACCEPT
3062 : RestorePolicy.IGNORE);
3063 // At this point we've consumed this file entry
3064 // ourselves, so just strip the tar footer and
3065 // go on to the next file in the input stream
3066 skipTarPadding(info.size, instream);
3067 return true;
3068 } else {
3069 // File data before (or without) the apk. We can't
3070 // handle it coherently in this case so ignore it.
3071 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3072 okay = false;
3073 }
3074 break;
3075
3076 case ACCEPT:
3077 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3078 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3079 // we can take the data without the apk, so we
3080 // *want* to do so. skip the apk by declaring this
3081 // one file not-okay without changing the restore
3082 // policy for the package.
3083 okay = false;
3084 }
3085 break;
3086
3087 default:
3088 // Something has gone dreadfully wrong when determining
3089 // the restore policy from the manifest. Ignore the
3090 // rest of this package's data.
3091 Slog.e(TAG, "Invalid policy from manifest");
3092 okay = false;
3093 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3094 break;
3095 }
3096
3097 // If the policy is satisfied, go ahead and set up to pipe the
3098 // data to the agent.
3099 if (DEBUG && okay && mAgent != null) {
3100 Slog.i(TAG, "Reusing existing agent instance");
3101 }
3102 if (okay && mAgent == null) {
3103 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3104
3105 try {
3106 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3107
3108 // If we haven't sent any data to this app yet, we probably
3109 // need to clear it first. Check that.
3110 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003111 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003112 // responsible for coherently managing a full
3113 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003114 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003115 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3116 clearApplicationDataSynchronous(pkg);
3117 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003118 if (DEBUG) Slog.d(TAG, "backup agent ("
3119 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003120 }
3121 mClearedPackages.add(pkg);
3122 } else {
3123 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3124 }
3125
3126 // All set; now set up the IPC and launch the agent
3127 setUpPipes();
3128 mAgent = bindToAgentSynchronous(mTargetApp,
3129 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3130 mAgentPackage = pkg;
3131 } catch (IOException e) {
3132 // fall through to error handling
3133 } catch (NameNotFoundException e) {
3134 // fall through to error handling
3135 }
3136
3137 if (mAgent == null) {
3138 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3139 okay = false;
3140 tearDownPipes();
3141 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3142 }
3143 }
3144
3145 // Sanity check: make sure we never give data to the wrong app. This
3146 // should never happen but a little paranoia here won't go amiss.
3147 if (okay && !pkg.equals(mAgentPackage)) {
3148 Slog.e(TAG, "Restoring data for " + pkg
3149 + " but agent is for " + mAgentPackage);
3150 okay = false;
3151 }
3152
3153 // At this point we have an agent ready to handle the full
3154 // restore data as well as a pipe for sending data to
3155 // that agent. Tell the agent to start reading from the
3156 // pipe.
3157 if (okay) {
3158 boolean agentSuccess = true;
3159 long toCopy = info.size;
3160 final int token = generateToken();
3161 try {
3162 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3163 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003164 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003165 // fire up the app's agent listening on the socket. If
3166 // the agent is running in the system process we can't
3167 // just invoke it asynchronously, so we provide a thread
3168 // for it here.
3169 if (mTargetApp.processName.equals("system")) {
3170 Slog.d(TAG, "system process agent - spinning a thread");
3171 RestoreFileRunnable runner = new RestoreFileRunnable(
3172 mAgent, info, mPipes[0], token);
3173 new Thread(runner).start();
3174 } else {
3175 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3176 info.domain, info.path, info.mode, info.mtime,
3177 token, mBackupManagerBinder);
3178 }
3179 } catch (IOException e) {
3180 // couldn't dup the socket for a process-local restore
3181 Slog.d(TAG, "Couldn't establish restore");
3182 agentSuccess = false;
3183 okay = false;
3184 } catch (RemoteException e) {
3185 // whoops, remote agent went away. We'll eat the content
3186 // ourselves, then, and not copy it over.
3187 Slog.e(TAG, "Agent crashed during full restore");
3188 agentSuccess = false;
3189 okay = false;
3190 }
3191
3192 // Copy over the data if the agent is still good
3193 if (okay) {
3194 boolean pipeOkay = true;
3195 FileOutputStream pipe = new FileOutputStream(
3196 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003197 while (toCopy > 0) {
3198 int toRead = (toCopy > buffer.length)
3199 ? buffer.length : (int)toCopy;
3200 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003201 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003202 if (nRead <= 0) break;
3203 toCopy -= nRead;
3204
3205 // send it to the output pipe as long as things
3206 // are still good
3207 if (pipeOkay) {
3208 try {
3209 pipe.write(buffer, 0, nRead);
3210 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003211 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003212 pipeOkay = false;
3213 }
3214 }
3215 }
3216
3217 // done sending that file! Now we just need to consume
3218 // the delta from info.size to the end of block.
3219 skipTarPadding(info.size, instream);
3220
3221 // and now that we've sent it all, wait for the remote
3222 // side to acknowledge receipt
3223 agentSuccess = waitUntilOperationComplete(token);
3224 }
3225
3226 // okay, if the remote end failed at any point, deal with
3227 // it by ignoring the rest of the restore on it
3228 if (!agentSuccess) {
3229 mBackupHandler.removeMessages(MSG_TIMEOUT);
3230 tearDownPipes();
3231 tearDownAgent(mTargetApp);
3232 mAgent = null;
3233 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3234 }
3235 }
3236
3237 // Problems setting up the agent communication, or an already-
3238 // ignored package: skip to the next tar stream entry by
3239 // reading and discarding this file.
3240 if (!okay) {
3241 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3242 long bytesToConsume = (info.size + 511) & ~511;
3243 while (bytesToConsume > 0) {
3244 int toRead = (bytesToConsume > buffer.length)
3245 ? buffer.length : (int)bytesToConsume;
3246 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003247 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003248 if (nRead <= 0) break;
3249 bytesToConsume -= nRead;
3250 }
3251 }
3252 }
3253 }
3254 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003255 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003256 // treat as EOF
3257 info = null;
3258 }
3259
3260 return (info != null);
3261 }
3262
3263 void setUpPipes() throws IOException {
3264 mPipes = ParcelFileDescriptor.createPipe();
3265 }
3266
3267 void tearDownPipes() {
3268 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003269 try {
3270 mPipes[0].close();
3271 mPipes[0] = null;
3272 mPipes[1].close();
3273 mPipes[1] = null;
3274 } catch (IOException e) {
3275 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003276 }
3277 mPipes = null;
3278 }
3279 }
3280
3281 void tearDownAgent(ApplicationInfo app) {
3282 if (mAgent != null) {
3283 try {
3284 // unbind and tidy up even on timeout or failure, just in case
3285 mActivityManager.unbindBackupAgent(app);
3286
3287 // The agent was running with a stub Application object, so shut it down.
3288 // !!! We hardcode the confirmation UI's package name here rather than use a
3289 // manifest flag! TODO something less direct.
3290 if (app.uid != Process.SYSTEM_UID
3291 && !app.packageName.equals("com.android.backupconfirm")) {
3292 if (DEBUG) Slog.d(TAG, "Killing host process");
3293 mActivityManager.killApplicationProcess(app.processName, app.uid);
3294 } else {
3295 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3296 }
3297 } catch (RemoteException e) {
3298 Slog.d(TAG, "Lost app trying to shut down");
3299 }
3300 mAgent = null;
3301 }
3302 }
3303
3304 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3305 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003306 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003307 int mResult;
3308
3309 public void reset() {
3310 synchronized (mDone) {
3311 mDone.set(false);
3312 }
3313 }
3314
3315 public void waitForCompletion() {
3316 synchronized (mDone) {
3317 while (mDone.get() == false) {
3318 try {
3319 mDone.wait();
3320 } catch (InterruptedException e) { }
3321 }
3322 }
3323 }
3324
3325 int getResult() {
3326 return mResult;
3327 }
3328
3329 @Override
3330 public void packageInstalled(String packageName, int returnCode)
3331 throws RemoteException {
3332 synchronized (mDone) {
3333 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003334 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003335 mDone.set(true);
3336 mDone.notifyAll();
3337 }
3338 }
3339 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003340
3341 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3342 final AtomicBoolean mDone = new AtomicBoolean();
3343 int mResult;
3344
3345 public void reset() {
3346 synchronized (mDone) {
3347 mDone.set(false);
3348 }
3349 }
3350
3351 public void waitForCompletion() {
3352 synchronized (mDone) {
3353 while (mDone.get() == false) {
3354 try {
3355 mDone.wait();
3356 } catch (InterruptedException e) { }
3357 }
3358 }
3359 }
3360
3361 @Override
3362 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3363 synchronized (mDone) {
3364 mResult = returnCode;
3365 mDone.set(true);
3366 mDone.notifyAll();
3367 }
3368 }
3369 }
3370
Christopher Tate75a99702011-05-18 16:28:19 -07003371 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003372 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003373
3374 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3375 boolean okay = true;
3376
3377 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3378
3379 // The file content is an .apk file. Copy it out to a staging location and
3380 // attempt to install it.
3381 File apkFile = new File(mDataDir, info.packageName);
3382 try {
3383 FileOutputStream apkStream = new FileOutputStream(apkFile);
3384 byte[] buffer = new byte[32 * 1024];
3385 long size = info.size;
3386 while (size > 0) {
3387 long toRead = (buffer.length < size) ? buffer.length : size;
3388 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003389 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003390 apkStream.write(buffer, 0, didRead);
3391 size -= didRead;
3392 }
3393 apkStream.close();
3394
3395 // make sure the installer can read it
3396 apkFile.setReadable(true, false);
3397
3398 // Now install it
3399 Uri packageUri = Uri.fromFile(apkFile);
3400 mInstallObserver.reset();
3401 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003402 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3403 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003404 mInstallObserver.waitForCompletion();
3405
3406 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3407 // The only time we continue to accept install of data even if the
3408 // apk install failed is if we had already determined that we could
3409 // accept the data regardless.
3410 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3411 okay = false;
3412 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003413 } else {
3414 // Okay, the install succeeded. Make sure it was the right app.
3415 boolean uninstall = false;
3416 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3417 Slog.w(TAG, "Restore stream claimed to include apk for "
3418 + info.packageName + " but apk was really "
3419 + mInstallObserver.mPackageName);
3420 // delete the package we just put in place; it might be fraudulent
3421 okay = false;
3422 uninstall = true;
3423 } else {
3424 try {
3425 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3426 PackageManager.GET_SIGNATURES);
3427 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3428 Slog.w(TAG, "Restore stream contains apk of package "
3429 + info.packageName + " but it disallows backup/restore");
3430 okay = false;
3431 } else {
3432 // So far so good -- do the signatures match the manifest?
3433 Signature[] sigs = mManifestSignatures.get(info.packageName);
3434 if (!signaturesMatch(sigs, pkg)) {
3435 Slog.w(TAG, "Installed app " + info.packageName
3436 + " signatures do not match restore manifest");
3437 okay = false;
3438 uninstall = true;
3439 }
3440 }
3441 } catch (NameNotFoundException e) {
3442 Slog.w(TAG, "Install of package " + info.packageName
3443 + " succeeded but now not found");
3444 okay = false;
3445 }
3446 }
3447
3448 // If we're not okay at this point, we need to delete the package
3449 // that we just installed.
3450 if (uninstall) {
3451 mDeleteObserver.reset();
3452 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3453 mDeleteObserver, 0);
3454 mDeleteObserver.waitForCompletion();
3455 }
Christopher Tate75a99702011-05-18 16:28:19 -07003456 }
3457 } catch (IOException e) {
3458 Slog.e(TAG, "Unable to transcribe restored apk for install");
3459 okay = false;
3460 } finally {
3461 apkFile.delete();
3462 }
3463
3464 return okay;
3465 }
3466
3467 // Given an actual file content size, consume the post-content padding mandated
3468 // by the tar format.
3469 void skipTarPadding(long size, InputStream instream) throws IOException {
3470 long partial = (size + 512) % 512;
3471 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003472 final int needed = 512 - (int)partial;
3473 byte[] buffer = new byte[needed];
3474 if (readExactly(instream, buffer, 0, needed) == needed) {
3475 mBytes += needed;
3476 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003477 }
3478 }
3479
3480 // Returns a policy constant; takes a buffer arg to reduce memory churn
3481 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3482 throws IOException {
3483 // Fail on suspiciously large manifest files
3484 if (info.size > 64 * 1024) {
3485 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3486 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003487
Christopher Tate75a99702011-05-18 16:28:19 -07003488 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003489 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3490 mBytes += info.size;
3491 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003492
3493 RestorePolicy policy = RestorePolicy.IGNORE;
3494 String[] str = new String[1];
3495 int offset = 0;
3496
3497 try {
3498 offset = extractLine(buffer, offset, str);
3499 int version = Integer.parseInt(str[0]);
3500 if (version == BACKUP_MANIFEST_VERSION) {
3501 offset = extractLine(buffer, offset, str);
3502 String manifestPackage = str[0];
3503 // TODO: handle <original-package>
3504 if (manifestPackage.equals(info.packageName)) {
3505 offset = extractLine(buffer, offset, str);
3506 version = Integer.parseInt(str[0]); // app version
3507 offset = extractLine(buffer, offset, str);
3508 int platformVersion = Integer.parseInt(str[0]);
3509 offset = extractLine(buffer, offset, str);
3510 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3511 offset = extractLine(buffer, offset, str);
3512 boolean hasApk = str[0].equals("1");
3513 offset = extractLine(buffer, offset, str);
3514 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003515 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003516 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003517 for (int i = 0; i < numSigs; i++) {
3518 offset = extractLine(buffer, offset, str);
3519 sigs[i] = new Signature(str[0]);
3520 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003521 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003522
3523 // Okay, got the manifest info we need...
3524 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003525 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3526 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003527 // Fall through to IGNORE if the app explicitly disallows backup
3528 final int flags = pkgInfo.applicationInfo.flags;
3529 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3530 // Verify signatures against any installed version; if they
3531 // don't match, then we fall though and ignore the data. The
3532 // signatureMatch() method explicitly ignores the signature
3533 // check for packages installed on the system partition, because
3534 // such packages are signed with the platform cert instead of
3535 // the app developer's cert, so they're different on every
3536 // device.
3537 if (signaturesMatch(sigs, pkgInfo)) {
3538 if (pkgInfo.versionCode >= version) {
3539 Slog.i(TAG, "Sig + version match; taking data");
3540 policy = RestorePolicy.ACCEPT;
3541 } else {
3542 // The data is from a newer version of the app than
3543 // is presently installed. That means we can only
3544 // use it if the matching apk is also supplied.
3545 Slog.d(TAG, "Data version " + version
3546 + " is newer than installed version "
3547 + pkgInfo.versionCode + " - requiring apk");
3548 policy = RestorePolicy.ACCEPT_IF_APK;
3549 }
Christopher Tate75a99702011-05-18 16:28:19 -07003550 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003551 Slog.w(TAG, "Restore manifest signatures do not match "
3552 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003553 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003554 } else {
3555 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3556 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003557 }
3558 } catch (NameNotFoundException e) {
3559 // Okay, the target app isn't installed. We can process
3560 // the restore properly only if the dataset provides the
3561 // apk file and we can successfully install it.
3562 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3563 + " not installed; requiring apk in dataset");
3564 policy = RestorePolicy.ACCEPT_IF_APK;
3565 }
3566
3567 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3568 Slog.i(TAG, "Cannot restore package " + info.packageName
3569 + " without the matching .apk");
3570 }
3571 } else {
3572 Slog.i(TAG, "Missing signature on backed-up package "
3573 + info.packageName);
3574 }
3575 } else {
3576 Slog.i(TAG, "Expected package " + info.packageName
3577 + " but restore manifest claims " + manifestPackage);
3578 }
3579 } else {
3580 Slog.i(TAG, "Unknown restore manifest version " + version
3581 + " for package " + info.packageName);
3582 }
3583 } catch (NumberFormatException e) {
3584 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003585 } catch (IllegalArgumentException e) {
3586 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003587 }
3588
3589 return policy;
3590 }
3591
3592 // Builds a line from a byte buffer starting at 'offset', and returns
3593 // the index of the next unconsumed data in the buffer.
3594 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3595 final int end = buffer.length;
3596 if (offset >= end) throw new IOException("Incomplete data");
3597
3598 int pos;
3599 for (pos = offset; pos < end; pos++) {
3600 byte c = buffer[pos];
3601 // at LF we declare end of line, and return the next char as the
3602 // starting point for the next time through
3603 if (c == '\n') {
3604 break;
3605 }
3606 }
3607 outStr[0] = new String(buffer, offset, pos - offset);
3608 pos++; // may be pointing an extra byte past the end but that's okay
3609 return pos;
3610 }
3611
3612 void dumpFileMetadata(FileMetadata info) {
3613 if (DEBUG) {
3614 StringBuilder b = new StringBuilder(128);
3615
3616 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003617 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003618 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3619 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3620 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3621 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3622 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3623 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3624 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3625 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3626 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3627 b.append(String.format(" %9d ", info.size));
3628
3629 Date stamp = new Date(info.mtime);
3630 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3631
3632 b.append(info.packageName);
3633 b.append(" :: ");
3634 b.append(info.domain);
3635 b.append(" :: ");
3636 b.append(info.path);
3637
3638 Slog.i(TAG, b.toString());
3639 }
3640 }
3641 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3642 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3643 byte[] block = new byte[512];
3644 FileMetadata info = null;
3645
3646 boolean gotHeader = readTarHeader(instream, block);
3647 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003648 try {
3649 // okay, presume we're okay, and extract the various metadata
3650 info = new FileMetadata();
3651 info.size = extractRadix(block, 124, 12, 8);
3652 info.mtime = extractRadix(block, 136, 12, 8);
3653 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003654
Christopher Tate2efd2db2011-07-19 16:32:49 -07003655 info.path = extractString(block, 345, 155); // prefix
3656 String path = extractString(block, 0, 100);
3657 if (path.length() > 0) {
3658 if (info.path.length() > 0) info.path += '/';
3659 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003660 }
Christopher Tate75a99702011-05-18 16:28:19 -07003661
Christopher Tate2efd2db2011-07-19 16:32:49 -07003662 // tar link indicator field: 1 byte at offset 156 in the header.
3663 int typeChar = block[156];
3664 if (typeChar == 'x') {
3665 // pax extended header, so we need to read that
3666 gotHeader = readPaxExtendedHeader(instream, info);
3667 if (gotHeader) {
3668 // and after a pax extended header comes another real header -- read
3669 // that to find the real file type
3670 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003671 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003672 if (!gotHeader) throw new IOException("Bad or missing pax header");
3673
3674 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003675 }
Christopher Tate75a99702011-05-18 16:28:19 -07003676
Christopher Tate2efd2db2011-07-19 16:32:49 -07003677 switch (typeChar) {
3678 case '0': info.type = BackupAgent.TYPE_FILE; break;
3679 case '5': {
3680 info.type = BackupAgent.TYPE_DIRECTORY;
3681 if (info.size != 0) {
3682 Slog.w(TAG, "Directory entry with nonzero size in header");
3683 info.size = 0;
3684 }
3685 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003686 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003687 case 0: {
3688 // presume EOF
3689 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3690 return null;
3691 }
3692 default: {
3693 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3694 throw new IOException("Unknown entity type " + typeChar);
3695 }
Christopher Tate75a99702011-05-18 16:28:19 -07003696 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003697
3698 // Parse out the path
3699 //
3700 // first: apps/shared/unrecognized
3701 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3702 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3703 // File in shared storage. !!! TODO: implement this.
3704 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3705 info.packageName = "com.android.sharedstoragebackup";
3706 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3707 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3708 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3709 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3710 // App content! Parse out the package name and domain
3711
3712 // strip the apps/ prefix
3713 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3714
3715 // extract the package name
3716 int slash = info.path.indexOf('/');
3717 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3718 info.packageName = info.path.substring(0, slash);
3719 info.path = info.path.substring(slash+1);
3720
3721 // if it's a manifest we're done, otherwise parse out the domains
3722 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3723 slash = info.path.indexOf('/');
3724 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3725 info.domain = info.path.substring(0, slash);
3726 // validate that it's one of the domains we understand
3727 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3728 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3729 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3730 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3731 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3732 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3733 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3734 throw new IOException("Unrecognized domain " + info.domain);
3735 }
3736
3737 info.path = info.path.substring(slash + 1);
3738 }
3739 }
3740 } catch (IOException e) {
3741 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003742 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003743 HEXLOG(block);
3744 }
3745 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003746 }
3747 }
3748 return info;
3749 }
3750
Christopher Tate2efd2db2011-07-19 16:32:49 -07003751 private void HEXLOG(byte[] block) {
3752 int offset = 0;
3753 int todo = block.length;
3754 StringBuilder buf = new StringBuilder(64);
3755 while (todo > 0) {
3756 buf.append(String.format("%04x ", offset));
3757 int numThisLine = (todo > 16) ? 16 : todo;
3758 for (int i = 0; i < numThisLine; i++) {
3759 buf.append(String.format("%02x ", block[offset+i]));
3760 }
3761 Slog.i("hexdump", buf.toString());
3762 buf.setLength(0);
3763 todo -= numThisLine;
3764 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003765 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003766 }
3767
Christopher Tate6853fcf2011-08-10 17:52:21 -07003768 // Read exactly the given number of bytes into a buffer at the stated offset.
3769 // Returns false if EOF is encountered before the requested number of bytes
3770 // could be read.
3771 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3772 throws IOException {
3773 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3774
3775 int soFar = 0;
3776 while (soFar < size) {
3777 int nRead = in.read(buffer, offset + soFar, size - soFar);
3778 if (nRead <= 0) {
3779 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3780 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003781 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003782 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003783 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003784 return soFar;
3785 }
3786
3787 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3788 final int got = readExactly(instream, block, 0, 512);
3789 if (got == 0) return false; // Clean EOF
3790 if (got < 512) throw new IOException("Unable to read full block header");
3791 mBytes += 512;
3792 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003793 }
3794
3795 // overwrites 'info' fields based on the pax extended header
3796 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3797 throws IOException {
3798 // We should never see a pax extended header larger than this
3799 if (info.size > 32*1024) {
3800 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3801 + " - aborting");
3802 throw new IOException("Sanity failure: pax header size " + info.size);
3803 }
3804
3805 // read whole blocks, not just the content size
3806 int numBlocks = (int)((info.size + 511) >> 9);
3807 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003808 if (readExactly(instream, data, 0, data.length) < data.length) {
3809 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003810 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003811 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003812
3813 final int contentSize = (int) info.size;
3814 int offset = 0;
3815 do {
3816 // extract the line at 'offset'
3817 int eol = offset+1;
3818 while (eol < contentSize && data[eol] != ' ') eol++;
3819 if (eol >= contentSize) {
3820 // error: we just hit EOD looking for the end of the size field
3821 throw new IOException("Invalid pax data");
3822 }
3823 // eol points to the space between the count and the key
3824 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3825 int key = eol + 1; // start of key=value
3826 eol = offset + linelen - 1; // trailing LF
3827 int value;
3828 for (value = key+1; data[value] != '=' && value <= eol; value++);
3829 if (value > eol) {
3830 throw new IOException("Invalid pax declaration");
3831 }
3832
3833 // pax requires that key/value strings be in UTF-8
3834 String keyStr = new String(data, key, value-key, "UTF-8");
3835 // -1 to strip the trailing LF
3836 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3837
3838 if ("path".equals(keyStr)) {
3839 info.path = valStr;
3840 } else if ("size".equals(keyStr)) {
3841 info.size = Long.parseLong(valStr);
3842 } else {
3843 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3844 }
3845
3846 offset += linelen;
3847 } while (offset < contentSize);
3848
3849 return true;
3850 }
3851
3852 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3853 throws IOException {
3854 long value = 0;
3855 final int end = offset + maxChars;
3856 for (int i = offset; i < end; i++) {
3857 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003858 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003859 if (b == 0 || b == ' ') break;
3860 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003861 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003862 }
3863 value = radix * value + (b - '0');
3864 }
3865 return value;
3866 }
3867
3868 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3869 final int end = offset + maxChars;
3870 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003871 // tar string fields terminate early with a NUL
3872 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003873 return new String(data, offset, eos-offset, "US-ASCII");
3874 }
3875
3876 void sendStartRestore() {
3877 if (mObserver != null) {
3878 try {
3879 mObserver.onStartRestore();
3880 } catch (RemoteException e) {
3881 Slog.w(TAG, "full restore observer went away: startRestore");
3882 mObserver = null;
3883 }
3884 }
3885 }
3886
3887 void sendOnRestorePackage(String name) {
3888 if (mObserver != null) {
3889 try {
3890 // TODO: use a more user-friendly name string
3891 mObserver.onRestorePackage(name);
3892 } catch (RemoteException e) {
3893 Slog.w(TAG, "full restore observer went away: restorePackage");
3894 mObserver = null;
3895 }
3896 }
3897 }
3898
3899 void sendEndRestore() {
3900 if (mObserver != null) {
3901 try {
3902 mObserver.onEndRestore();
3903 } catch (RemoteException e) {
3904 Slog.w(TAG, "full restore observer went away: endRestore");
3905 mObserver = null;
3906 }
3907 }
3908 }
3909 }
3910
Christopher Tatedf01dea2009-06-09 20:45:02 -07003911 // ----- Restore handling -----
3912
Christopher Tate78dd4a72009-11-04 11:49:08 -08003913 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3914 // If the target resides on the system partition, we allow it to restore
3915 // data from the like-named package in a restore set even if the signatures
3916 // do not match. (Unlike general applications, those flashed to the system
3917 // partition will be signed with the device's platform certificate, so on
3918 // different phones the same system app will have different signatures.)
3919 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003920 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003921 return true;
3922 }
3923
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003924 // Allow unsigned apps, but not signed on one device and unsigned on the other
3925 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003926 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003927 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003928 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003929 if ((storedSigs == null || storedSigs.length == 0)
3930 && (deviceSigs == null || deviceSigs.length == 0)) {
3931 return true;
3932 }
3933 if (storedSigs == null || deviceSigs == null) {
3934 return false;
3935 }
3936
Christopher Tateabce4e82009-06-18 18:35:32 -07003937 // !!! TODO: this demands that every stored signature match one
3938 // that is present on device, and does not demand the converse.
3939 // Is this this right policy?
3940 int nStored = storedSigs.length;
3941 int nDevice = deviceSigs.length;
3942
3943 for (int i=0; i < nStored; i++) {
3944 boolean match = false;
3945 for (int j=0; j < nDevice; j++) {
3946 if (storedSigs[i].equals(deviceSigs[j])) {
3947 match = true;
3948 break;
3949 }
3950 }
3951 if (!match) {
3952 return false;
3953 }
3954 }
3955 return true;
3956 }
3957
Christopher Tate2982d062011-09-06 20:35:24 -07003958 enum RestoreState {
3959 INITIAL,
3960 DOWNLOAD_DATA,
3961 PM_METADATA,
3962 RUNNING_QUEUE,
3963 FINAL
3964 }
3965
3966 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003967 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003968 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003969 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003970 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003971 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003972 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003973 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003974 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07003975 private long mStartRealtime;
3976 private PackageManagerBackupAgent mPmAgent;
3977 private List<PackageInfo> mAgentPackages;
3978 private ArrayList<PackageInfo> mRestorePackages;
3979 private RestoreState mCurrentState;
3980 private int mCount;
3981 private boolean mFinished;
3982 private int mStatus;
3983 private File mBackupDataName;
3984 private File mNewStateName;
3985 private File mSavedStateName;
3986 private ParcelFileDescriptor mBackupData;
3987 private ParcelFileDescriptor mNewState;
3988 private PackageInfo mCurrentPackage;
3989
Christopher Tatedf01dea2009-06-09 20:45:02 -07003990
Christopher Tate5cbbf562009-06-22 16:44:51 -07003991 class RestoreRequest {
3992 public PackageInfo app;
3993 public int storedAppVersion;
3994
3995 RestoreRequest(PackageInfo _app, int _version) {
3996 app = _app;
3997 storedAppVersion = _version;
3998 }
3999 }
4000
Christopher Tate44a27902010-01-27 17:15:49 -08004001 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004002 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004003 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004004 mCurrentState = RestoreState.INITIAL;
4005 mFinished = false;
4006 mPmAgent = null;
4007
Christopher Tatedf01dea2009-06-09 20:45:02 -07004008 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004009 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004010 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004011 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004012 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004013 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004014
Christopher Tate284f1bb2011-07-07 14:31:18 -07004015 if (filterSet != null) {
4016 mFilterSet = new HashSet<String>();
4017 for (String pkg : filterSet) {
4018 mFilterSet.add(pkg);
4019 }
4020 } else {
4021 mFilterSet = null;
4022 }
4023
Christopher Tate5cb400b2009-06-25 16:03:14 -07004024 try {
4025 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4026 } catch (RemoteException e) {
4027 // can't happen; the transport is local
4028 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004029 }
4030
Christopher Tate2982d062011-09-06 20:35:24 -07004031 // Execute one tick of whatever state machine the task implements
4032 @Override
4033 public void execute() {
4034 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4035 switch (mCurrentState) {
4036 case INITIAL:
4037 beginRestore();
4038 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004039
Christopher Tate2982d062011-09-06 20:35:24 -07004040 case DOWNLOAD_DATA:
4041 downloadRestoreData();
4042 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004043
Christopher Tate2982d062011-09-06 20:35:24 -07004044 case PM_METADATA:
4045 restorePmMetadata();
4046 break;
4047
4048 case RUNNING_QUEUE:
4049 restoreNextAgent();
4050 break;
4051
4052 case FINAL:
4053 if (!mFinished) finalizeRestore();
4054 else {
4055 Slog.e(TAG, "Duplicate finish");
4056 }
4057 mFinished = true;
4058 break;
4059 }
4060 }
4061
4062 // Initialize and set up for the PM metadata restore, which comes first
4063 void beginRestore() {
4064 // Don't account time doing the restore as inactivity of the app
4065 // that has opened a restore session.
4066 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4067
4068 // Assume error until we successfully init everything
4069 mStatus = BackupConstants.TRANSPORT_ERROR;
4070
Christopher Tatedf01dea2009-06-09 20:45:02 -07004071 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004072 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004073 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004074
Dan Egnorefe52642009-06-24 00:16:33 -07004075 // Get the list of all packages which have backup enabled.
4076 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004077 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004078 PackageInfo omPackage = new PackageInfo();
4079 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004080 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004081
Christopher Tate2982d062011-09-06 20:35:24 -07004082 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004083 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004084 // if there's a filter set, strip out anything that isn't
4085 // present before proceeding
4086 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004087 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4088 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004089 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004090 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004091 }
4092 }
Christopher Tate2982d062011-09-06 20:35:24 -07004093 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004094 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004095 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004096 Slog.i(TAG, " " + p);
4097 }
4098 }
4099 }
Christopher Tate2982d062011-09-06 20:35:24 -07004100 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004101 } else {
4102 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004103 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004104 }
Dan Egnorefe52642009-06-24 00:16:33 -07004105
Christopher Tate7d562ec2009-06-25 18:03:43 -07004106 // let the observer know that we're running
4107 if (mObserver != null) {
4108 try {
4109 // !!! TODO: get an actual count from the transport after
4110 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004111 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004112 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004113 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004114 mObserver = null;
4115 }
4116 }
Christopher Tate2982d062011-09-06 20:35:24 -07004117 } catch (RemoteException e) {
4118 // Something has gone catastrophically wrong with the transport
4119 Slog.e(TAG, "Error communicating with transport for restore");
4120 executeNextState(RestoreState.FINAL);
4121 return;
4122 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004123
Christopher Tate2982d062011-09-06 20:35:24 -07004124 mStatus = BackupConstants.TRANSPORT_OK;
4125 executeNextState(RestoreState.DOWNLOAD_DATA);
4126 }
4127
4128 void downloadRestoreData() {
4129 // Note that the download phase can be very time consuming, but we're executing
4130 // it inline here on the looper. This is "okay" because it is not calling out to
4131 // third party code; the transport is "trusted," and so we assume it is being a
4132 // good citizen and timing out etc when appropriate.
4133 //
4134 // TODO: when appropriate, move the download off the looper and rearrange the
4135 // error handling around that.
4136 try {
4137 mStatus = mTransport.startRestore(mToken,
4138 mRestorePackages.toArray(new PackageInfo[0]));
4139 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004141 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004142 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004143 return;
4144 }
Christopher Tate2982d062011-09-06 20:35:24 -07004145 } catch (RemoteException e) {
4146 Slog.e(TAG, "Error communicating with transport for restore");
4147 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4148 mStatus = BackupConstants.TRANSPORT_ERROR;
4149 executeNextState(RestoreState.FINAL);
4150 return;
4151 }
Dan Egnorefe52642009-06-24 00:16:33 -07004152
Christopher Tate2982d062011-09-06 20:35:24 -07004153 // Successful download of the data to be parceled out to the apps, so off we go.
4154 executeNextState(RestoreState.PM_METADATA);
4155 }
4156
4157 void restorePmMetadata() {
4158 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004159 String packageName = mTransport.nextRestorePackage();
4160 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004161 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004162 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004163 mStatus = BackupConstants.TRANSPORT_ERROR;
4164 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004165 return;
4166 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004167 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004168 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004169 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004170 mStatus = BackupConstants.TRANSPORT_OK;
4171 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004172 return;
4173 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004174 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004175 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004176 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004177 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004178 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004179 return;
4180 }
4181
4182 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004183 PackageInfo omPackage = new PackageInfo();
4184 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4185 mPmAgent = new PackageManagerBackupAgent(
4186 mPackageManager, mAgentPackages);
4187 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004188 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004189 // The PM agent called operationComplete() already, because our invocation
4190 // of it is process-local and therefore synchronous. That means that a
4191 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4192 // proceed with running the queue do we remove that pending message and
4193 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004194
Christopher Tate8c032472009-07-02 14:28:47 -07004195 // Verify that the backup set includes metadata. If not, we can't do
4196 // signature/version verification etc, so we simply do not proceed with
4197 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004198 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004199 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004200 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004201 "Package manager restore metadata missing");
4202 mStatus = BackupConstants.TRANSPORT_ERROR;
4203 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4204 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004205 return;
4206 }
Christopher Tate2982d062011-09-06 20:35:24 -07004207 } catch (RemoteException e) {
4208 Slog.e(TAG, "Error communicating with transport for restore");
4209 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4210 mStatus = BackupConstants.TRANSPORT_ERROR;
4211 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4212 executeNextState(RestoreState.FINAL);
4213 return;
4214 }
Christopher Tate8c032472009-07-02 14:28:47 -07004215
Christopher Tate2982d062011-09-06 20:35:24 -07004216 // Metadata is intact, so we can now run the restore queue. If we get here,
4217 // we have already enqueued the necessary next-step message on the looper.
4218 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004219
Christopher Tate2982d062011-09-06 20:35:24 -07004220 void restoreNextAgent() {
4221 try {
4222 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004223
Christopher Tate2982d062011-09-06 20:35:24 -07004224 if (packageName == null) {
4225 Slog.e(TAG, "Error getting next restore package");
4226 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4227 executeNextState(RestoreState.FINAL);
4228 return;
4229 } else if (packageName.equals("")) {
4230 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4231 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4232 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4233 executeNextState(RestoreState.FINAL);
4234 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004235 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004236
4237 if (mObserver != null) {
4238 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004239 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004240 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004241 Slog.d(TAG, "Restore observer died in onUpdate");
4242 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004243 }
4244 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004245
Christopher Tate2982d062011-09-06 20:35:24 -07004246 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4247 if (metaInfo == null) {
4248 Slog.e(TAG, "Missing metadata for " + packageName);
4249 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4250 "Package metadata missing");
4251 executeNextState(RestoreState.RUNNING_QUEUE);
4252 return;
Christopher Tate84725812010-02-04 15:52:40 -08004253 }
4254
Christopher Tate2982d062011-09-06 20:35:24 -07004255 PackageInfo packageInfo;
4256 try {
4257 int flags = PackageManager.GET_SIGNATURES;
4258 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4259 } catch (NameNotFoundException e) {
4260 Slog.e(TAG, "Invalid package restoring data", e);
4261 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4262 "Package missing on device");
4263 executeNextState(RestoreState.RUNNING_QUEUE);
4264 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004265 }
4266
Christopher Tate2982d062011-09-06 20:35:24 -07004267 if (metaInfo.versionCode > packageInfo.versionCode) {
4268 // Data is from a "newer" version of the app than we have currently
4269 // installed. If the app has not declared that it is prepared to
4270 // handle this case, we do not attempt the restore.
4271 if ((packageInfo.applicationInfo.flags
4272 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4273 String message = "Version " + metaInfo.versionCode
4274 + " > installed version " + packageInfo.versionCode;
4275 Slog.w(TAG, "Package " + packageName + ": " + message);
4276 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4277 packageName, message);
4278 executeNextState(RestoreState.RUNNING_QUEUE);
4279 return;
4280 } else {
4281 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4282 + " > installed " + packageInfo.versionCode
4283 + " but restoreAnyVersion");
4284 }
4285 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004286
Christopher Tate2982d062011-09-06 20:35:24 -07004287 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4288 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4289 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4290 "Signature mismatch");
4291 executeNextState(RestoreState.RUNNING_QUEUE);
4292 return;
4293 }
4294
4295 if (DEBUG) Slog.v(TAG, "Package " + packageName
4296 + " restore version [" + metaInfo.versionCode
4297 + "] is compatible with installed version ["
4298 + packageInfo.versionCode + "]");
4299
4300 // Then set up and bind the agent
4301 IBackupAgent agent = bindToAgentSynchronous(
4302 packageInfo.applicationInfo,
4303 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4304 if (agent == null) {
4305 Slog.w(TAG, "Can't find backup agent for " + packageName);
4306 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4307 "Restore agent missing");
4308 executeNextState(RestoreState.RUNNING_QUEUE);
4309 return;
4310 }
4311
4312 // And then finally start the restore on this agent
4313 try {
4314 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4315 ++mCount;
4316 } catch (Exception e) {
4317 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4318 agentErrorCleanup();
4319 executeNextState(RestoreState.RUNNING_QUEUE);
4320 }
4321 } catch (RemoteException e) {
4322 Slog.e(TAG, "Unable to fetch restore data from transport");
4323 mStatus = BackupConstants.TRANSPORT_ERROR;
4324 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004325 }
4326 }
4327
Christopher Tate2982d062011-09-06 20:35:24 -07004328 void finalizeRestore() {
4329 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4330
4331 try {
4332 mTransport.finishRestore();
4333 } catch (RemoteException e) {
4334 Slog.e(TAG, "Error finishing restore", e);
4335 }
4336
4337 if (mObserver != null) {
4338 try {
4339 mObserver.restoreFinished(mStatus);
4340 } catch (RemoteException e) {
4341 Slog.d(TAG, "Restore observer died at restoreFinished");
4342 }
4343 }
4344
4345 // If this was a restoreAll operation, record that this was our
4346 // ancestral dataset, as well as the set of apps that are possibly
4347 // restoreable from the dataset
4348 if (mTargetPackage == null && mPmAgent != null) {
4349 mAncestralPackages = mPmAgent.getRestoredPackages();
4350 mAncestralToken = mToken;
4351 writeRestoreTokens();
4352 }
4353
4354 // We must under all circumstances tell the Package Manager to
4355 // proceed with install notifications if it's waiting for us.
4356 if (mPmToken > 0) {
4357 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4358 try {
4359 mPackageManagerBinder.finishPackageInstall(mPmToken);
4360 } catch (RemoteException e) { /* can't happen */ }
4361 }
4362
4363 // Furthermore we need to reset the session timeout clock
4364 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4365 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4366 TIMEOUT_RESTORE_INTERVAL);
4367
4368 // done; we can finally release the wakelock
4369 Slog.i(TAG, "Restore complete.");
4370 mWakelock.release();
4371 }
4372
4373 // Call asynchronously into the app, passing it the restore data. The next step
4374 // after this is always a callback, either operationComplete() or handleTimeout().
4375 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004376 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004377 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004378 final String packageName = app.packageName;
4379
Christopher Tate2982d062011-09-06 20:35:24 -07004380 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004381
Christopher Tatec7b31e32009-06-10 15:49:30 -07004382 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004383 mBackupDataName = new File(mDataDir, packageName + ".restore");
4384 mNewStateName = new File(mStateDir, packageName + ".new");
4385 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004386
Christopher Tate4a627c72011-04-01 14:43:32 -07004387 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004388 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004389 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004390 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004391 ParcelFileDescriptor.MODE_READ_WRITE |
4392 ParcelFileDescriptor.MODE_CREATE |
4393 ParcelFileDescriptor.MODE_TRUNCATE);
4394
Christopher Tate2982d062011-09-06 20:35:24 -07004395 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004396 // Transport-level failure, so we wind everything up and
4397 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004398 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004399 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004400 mBackupData.close();
4401 mBackupDataName.delete();
4402 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004403 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004404 }
4405
4406 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004407 mBackupData.close();
4408 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004409 ParcelFileDescriptor.MODE_READ_ONLY);
4410
Christopher Tate2982d062011-09-06 20:35:24 -07004411 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004412 ParcelFileDescriptor.MODE_READ_WRITE |
4413 ParcelFileDescriptor.MODE_CREATE |
4414 ParcelFileDescriptor.MODE_TRUNCATE);
4415
Christopher Tate44a27902010-01-27 17:15:49 -08004416 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004417 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4418 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004419 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004420 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004421 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004422 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004423
Christopher Tate2982d062011-09-06 20:35:24 -07004424 // After a restore failure we go back to running the queue. If there
4425 // are no more packages to be restored that will be handled by the
4426 // next step.
4427 executeNextState(RestoreState.RUNNING_QUEUE);
4428 }
4429 }
Chris Tate249345b2010-10-29 12:57:04 -07004430
Christopher Tate2982d062011-09-06 20:35:24 -07004431 void agentErrorCleanup() {
4432 // If the agent fails restore, it might have put the app's data
4433 // into an incoherent state. For consistency we wipe its data
4434 // again in this case before continuing with normal teardown
4435 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4436 agentCleanup();
4437 }
4438
4439 void agentCleanup() {
4440 mBackupDataName.delete();
4441 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4442 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4443 mBackupData = mNewState = null;
4444
4445 // if everything went okay, remember the recorded state now
4446 //
4447 // !!! TODO: the restored data should be migrated on the server
4448 // side into the current dataset. In that case the new state file
4449 // we just created would reflect the data already extant in the
4450 // backend, so there'd be nothing more to do. Until that happens,
4451 // however, we need to make sure that we record the data to the
4452 // current backend dataset. (Yes, this means shipping the data over
4453 // the wire in both directions. That's bad, but consistency comes
4454 // first, then efficiency.) Once we introduce server-side data
4455 // migration to the newly-restored device's dataset, we will change
4456 // the following from a discard of the newly-written state to the
4457 // "correct" operation of renaming into the canonical state blob.
4458 mNewStateName.delete(); // TODO: remove; see above comment
4459 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4460
4461 // If this wasn't the PM pseudopackage, tear down the agent side
4462 if (mCurrentPackage.applicationInfo != null) {
4463 // unbind and tidy up even on timeout or failure
4464 try {
4465 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4466
4467 // The agent was probably running with a stub Application object,
4468 // which isn't a valid run mode for the main app logic. Shut
4469 // down the app so that next time it's launched, it gets the
4470 // usual full initialization. Note that this is only done for
4471 // full-system restores: when a single app has requested a restore,
4472 // it is explicitly not killed following that operation.
4473 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4474 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4475 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4476 + mCurrentPackage.applicationInfo.processName);
4477 mActivityManager.killApplicationProcess(
4478 mCurrentPackage.applicationInfo.processName,
4479 mCurrentPackage.applicationInfo.uid);
4480 }
4481 } catch (RemoteException e) {
4482 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004483 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004484 }
Christopher Tate2982d062011-09-06 20:35:24 -07004485
4486 // The caller is responsible for reestablishing the state machine; our
4487 // responsibility here is to clear the decks for whatever comes next.
4488 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4489 synchronized (mCurrentOpLock) {
4490 mCurrentOperations.clear();
4491 }
4492 }
4493
4494 // A call to agent.doRestore() has been positively acknowledged as complete
4495 @Override
4496 public void operationComplete() {
4497 int size = (int) mBackupDataName.length();
4498 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4499 // Just go back to running the restore queue
4500 agentCleanup();
4501
4502 executeNextState(RestoreState.RUNNING_QUEUE);
4503 }
4504
4505 // A call to agent.doRestore() has timed out
4506 @Override
4507 public void handleTimeout() {
4508 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4509 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4510 mCurrentPackage.packageName, "restore timeout");
4511 // Handle like an agent that threw on invocation: wipe it and go on to the next
4512 agentErrorCleanup();
4513 executeNextState(RestoreState.RUNNING_QUEUE);
4514 }
4515
4516 void executeNextState(RestoreState nextState) {
4517 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4518 + this + " nextState=" + nextState);
4519 mCurrentState = nextState;
4520 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4521 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004522 }
4523 }
4524
Christopher Tate44a27902010-01-27 17:15:49 -08004525 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004526 IBackupTransport mTransport;
4527 PackageInfo mPackage;
4528
Christopher Tate44a27902010-01-27 17:15:49 -08004529 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004530 mTransport = transport;
4531 mPackage = packageInfo;
4532 }
4533
Christopher Tateee0e78a2009-07-02 11:17:03 -07004534 public void run() {
4535 try {
4536 // Clear the on-device backup state to ensure a full backup next time
4537 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4538 File stateFile = new File(stateDir, mPackage.packageName);
4539 stateFile.delete();
4540
4541 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004542 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004543 mTransport.clearBackupData(mPackage);
4544 } catch (RemoteException e) {
4545 // can't happen; the transport is local
4546 } finally {
4547 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004548 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004549 mTransport.finishBackup();
4550 } catch (RemoteException e) {
4551 // can't happen; the transport is local
4552 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004553
4554 // Last but not least, release the cpu
4555 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004556 }
4557 }
4558 }
4559
Christopher Tate44a27902010-01-27 17:15:49 -08004560 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004561 HashSet<String> mQueue;
4562
Christopher Tate44a27902010-01-27 17:15:49 -08004563 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004564 mQueue = transportNames;
4565 }
4566
Christopher Tate4cc86e12009-09-21 19:36:51 -07004567 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004568 try {
4569 for (String transportName : mQueue) {
4570 IBackupTransport transport = getTransport(transportName);
4571 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004572 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004573 continue;
4574 }
4575
Joe Onorato8a9b2202010-02-26 18:56:32 -08004576 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004577 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004578 long startRealtime = SystemClock.elapsedRealtime();
4579 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004580
Christopher Tate4cc86e12009-09-21 19:36:51 -07004581 if (status == BackupConstants.TRANSPORT_OK) {
4582 status = transport.finishBackup();
4583 }
4584
4585 // Okay, the wipe really happened. Clean up our local bookkeeping.
4586 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004587 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004588 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004589 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004590 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004591 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004592 synchronized (mQueueLock) {
4593 recordInitPendingLocked(false, transportName);
4594 }
Dan Egnor726247c2009-09-29 19:12:31 -07004595 } else {
4596 // If this didn't work, requeue this one and try again
4597 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004598 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004599 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004600 synchronized (mQueueLock) {
4601 recordInitPendingLocked(true, transportName);
4602 }
4603 // do this via another alarm to make sure of the wakelock states
4604 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004605 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004606 + transportName + " resched in " + delay);
4607 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4608 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004609 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004610 }
4611 } catch (RemoteException e) {
4612 // can't happen; the transports are local
4613 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004614 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004615 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004616 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004617 mWakelock.release();
4618 }
4619 }
4620 }
4621
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004622 private void dataChangedImpl(String packageName) {
4623 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4624 dataChangedImpl(packageName, targets);
4625 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004626
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004627 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004628 // Record that we need a backup pass for the caller. Since multiple callers
4629 // may share a uid, we need to note all candidates within that uid and schedule
4630 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004631 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004632
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004633 if (targets == null) {
4634 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4635 + " uid=" + Binder.getCallingUid());
4636 return;
4637 }
4638
4639 synchronized (mQueueLock) {
4640 // Note that this client has made data changes that need to be backed up
4641 for (ApplicationInfo app : targets) {
4642 // validate the caller-supplied package name against the known set of
4643 // packages associated with this uid
4644 if (app.packageName.equals(packageName)) {
4645 // Add the caller to the set of pending backups. If there is
4646 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004647 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004648 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004649 // Journal this request in case of crash. The put()
4650 // operation returned null when this package was not already
4651 // in the set; we want to avoid touching the disk redundantly.
4652 writeToJournalLocked(packageName);
4653
Christopher Tatec58efa62011-08-01 19:20:14 -07004654 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004655 int numKeys = mPendingBackups.size();
4656 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4657 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004658 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004659 }
4660 }
4661 }
4662 }
4663 }
4664 }
4665 }
4666
4667 // Note: packageName is currently unused, but may be in the future
4668 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004669 // If the caller does not hold the BACKUP permission, it can only request a
4670 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004671 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004672 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004673 synchronized (mBackupParticipants) {
4674 return mBackupParticipants.get(Binder.getCallingUid());
4675 }
4676 }
4677
4678 // a caller with full permission can ask to back up any participating app
4679 // !!! TODO: allow backup of ANY app?
4680 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4681 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004682 int N = mBackupParticipants.size();
4683 for (int i = 0; i < N; i++) {
4684 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4685 if (s != null) {
4686 targets.addAll(s);
4687 }
4688 }
4689 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004690 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004691 }
Christopher Tate46758122009-05-06 11:22:00 -07004692
Christopher Tatecde87f42009-06-12 12:55:53 -07004693 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004694 RandomAccessFile out = null;
4695 try {
4696 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4697 out = new RandomAccessFile(mJournal, "rws");
4698 out.seek(out.length());
4699 out.writeUTF(str);
4700 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004701 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004702 mJournal = null;
4703 } finally {
4704 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004705 }
4706 }
4707
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004708 // ----- IBackupManager binder interface -----
4709
4710 public void dataChanged(final String packageName) {
4711 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4712 if (targets == null) {
4713 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4714 + " uid=" + Binder.getCallingUid());
4715 return;
4716 }
4717
4718 mBackupHandler.post(new Runnable() {
4719 public void run() {
4720 dataChangedImpl(packageName, targets);
4721 }
4722 });
4723 }
4724
Christopher Tateee0e78a2009-07-02 11:17:03 -07004725 // Clear the given package's backup data from the current transport
4726 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004727 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004728 PackageInfo info;
4729 try {
4730 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4731 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004732 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004733 return;
4734 }
4735
4736 // If the caller does not hold the BACKUP permission, it can only request a
4737 // wipe of its own backed-up data.
4738 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004739 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004740 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4741 apps = mBackupParticipants.get(Binder.getCallingUid());
4742 } else {
4743 // a caller with full permission can ask to back up any participating app
4744 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004745 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004746 apps = new HashSet<ApplicationInfo>();
4747 int N = mBackupParticipants.size();
4748 for (int i = 0; i < N; i++) {
4749 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4750 if (s != null) {
4751 apps.addAll(s);
4752 }
4753 }
4754 }
4755
4756 // now find the given package in the set of candidate apps
4757 for (ApplicationInfo app : apps) {
4758 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004759 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004760 // found it; fire off the clear request
4761 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004762 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004763 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004764 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4765 new ClearParams(getTransport(mCurrentTransport), info));
4766 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004767 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004768 }
4769 break;
4770 }
4771 }
4772 }
4773
Christopher Tateace7f092009-06-15 18:07:25 -07004774 // Run a backup pass immediately for any applications that have declared
4775 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004776 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004778
Joe Onorato8a9b2202010-02-26 18:56:32 -08004779 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004780 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004781 // Because the alarms we are using can jitter, and we want an *immediate*
4782 // backup pass to happen, we restart the timer beginning with "next time,"
4783 // then manually fire the backup trigger intent ourselves.
4784 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004785 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004786 mRunBackupIntent.send();
4787 } catch (PendingIntent.CanceledException e) {
4788 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004789 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004790 }
Christopher Tate46758122009-05-06 11:22:00 -07004791 }
4792 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004793
Christopher Tated2c0cd42011-09-15 15:51:29 -07004794 boolean deviceIsProvisioned() {
4795 final ContentResolver resolver = mContext.getContentResolver();
4796 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4797 }
4798
Christopher Tate4a627c72011-04-01 14:43:32 -07004799 // Run a *full* backup pass for the given package, writing the resulting data stream
4800 // to the supplied file descriptor. This method is synchronous and does not return
4801 // to the caller until the backup has been completed.
4802 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004803 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004804 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4805
4806 // Validate
4807 if (!doAllApps) {
4808 if (!includeShared) {
4809 // If we're backing up shared data (sdcard or equivalent), then we can run
4810 // without any supplied app names. Otherwise, we'd be doing no work, so
4811 // report the error.
4812 if (pkgList == null || pkgList.length == 0) {
4813 throw new IllegalArgumentException(
4814 "Backup requested but neither shared nor any apps named");
4815 }
4816 }
4817 }
4818
Christopher Tate4a627c72011-04-01 14:43:32 -07004819 long oldId = Binder.clearCallingIdentity();
4820 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004821 // Doesn't make sense to do a full backup prior to setup
4822 if (!deviceIsProvisioned()) {
4823 Slog.i(TAG, "Full backup not supported before setup");
4824 return;
4825 }
4826
4827 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4828 + " shared=" + includeShared + " all=" + doAllApps
4829 + " pkgs=" + pkgList);
4830 Slog.i(TAG, "Beginning full backup...");
4831
Christopher Tate4a627c72011-04-01 14:43:32 -07004832 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004833 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004834 final int token = generateToken();
4835 synchronized (mFullConfirmations) {
4836 mFullConfirmations.put(token, params);
4837 }
4838
Christopher Tate75a99702011-05-18 16:28:19 -07004839 // start up the confirmation UI
4840 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4841 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4842 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004843 mFullConfirmations.delete(token);
4844 return;
4845 }
Christopher Tate75a99702011-05-18 16:28:19 -07004846
4847 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004848 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4849
4850 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004851 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004852
4853 // wait for the backup to be performed
4854 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4855 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004856 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004857 try {
4858 fd.close();
4859 } catch (IOException e) {
4860 // just eat it
4861 }
Christopher Tate75a99702011-05-18 16:28:19 -07004862 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004863 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07004864 }
Christopher Tate75a99702011-05-18 16:28:19 -07004865 }
4866
4867 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004868 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004869
4870 long oldId = Binder.clearCallingIdentity();
4871
4872 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004873 // Check whether the device has been provisioned -- we don't handle
4874 // full restores prior to completing the setup process.
4875 if (!deviceIsProvisioned()) {
4876 Slog.i(TAG, "Full restore not permitted before setup");
4877 return;
4878 }
4879
4880 Slog.i(TAG, "Beginning full restore...");
4881
Christopher Tate75a99702011-05-18 16:28:19 -07004882 FullRestoreParams params = new FullRestoreParams(fd);
4883 final int token = generateToken();
4884 synchronized (mFullConfirmations) {
4885 mFullConfirmations.put(token, params);
4886 }
4887
4888 // start up the confirmation UI
4889 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4890 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4891 Slog.e(TAG, "Unable to launch full restore confirmation");
4892 mFullConfirmations.delete(token);
4893 return;
4894 }
4895
4896 // make sure the screen is lit for the user interaction
4897 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4898
4899 // start the confirmation countdown
4900 startConfirmationTimeout(token, params);
4901
4902 // wait for the restore to be performed
4903 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4904 waitForCompletion(params);
4905 } finally {
4906 try {
4907 fd.close();
4908 } catch (IOException e) {
4909 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4910 }
4911 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004912 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07004913 }
4914 }
4915
4916 boolean startConfirmationUi(int token, String action) {
4917 try {
4918 Intent confIntent = new Intent(action);
4919 confIntent.setClassName("com.android.backupconfirm",
4920 "com.android.backupconfirm.BackupRestoreConfirmation");
4921 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4922 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4923 mContext.startActivity(confIntent);
4924 } catch (ActivityNotFoundException e) {
4925 return false;
4926 }
4927 return true;
4928 }
4929
4930 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004931 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004932 + TIMEOUT_FULL_CONFIRMATION + " millis");
4933 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4934 token, 0, params);
4935 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004936 }
4937
4938 void waitForCompletion(FullParams params) {
4939 synchronized (params.latch) {
4940 while (params.latch.get() == false) {
4941 try {
4942 params.latch.wait();
4943 } catch (InterruptedException e) { /* never interrupted */ }
4944 }
4945 }
4946 }
4947
4948 void signalFullBackupRestoreCompletion(FullParams params) {
4949 synchronized (params.latch) {
4950 params.latch.set(true);
4951 params.latch.notifyAll();
4952 }
4953 }
4954
4955 // Confirm that the previously-requested full backup/restore operation can proceed. This
4956 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004957 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004958 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004959 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004960 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4961 + " allow=" + allow);
4962
4963 // TODO: possibly require not just this signature-only permission, but even
4964 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004965 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004966
4967 long oldId = Binder.clearCallingIdentity();
4968 try {
4969
4970 FullParams params;
4971 synchronized (mFullConfirmations) {
4972 params = mFullConfirmations.get(token);
4973 if (params != null) {
4974 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4975 mFullConfirmations.delete(token);
4976
4977 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004978 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004979 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004980 : MSG_RUN_FULL_RESTORE;
4981
Christopher Tate728a1c42011-07-28 18:03:03 -07004982 params.observer = observer;
4983 params.curPassword = curPassword;
4984 params.encryptPassword = encPpassword;
4985
Christopher Tate75a99702011-05-18 16:28:19 -07004986 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004987 mWakelock.acquire();
4988 Message msg = mBackupHandler.obtainMessage(verb, params);
4989 mBackupHandler.sendMessage(msg);
4990 } else {
4991 Slog.w(TAG, "User rejected full backup/restore operation");
4992 // indicate completion without having actually transferred any data
4993 signalFullBackupRestoreCompletion(params);
4994 }
4995 } else {
4996 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4997 }
4998 }
4999 } finally {
5000 Binder.restoreCallingIdentity(oldId);
5001 }
5002 }
5003
Christopher Tate8031a3d2009-07-06 16:36:05 -07005004 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005005 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005007 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005008
Joe Onorato8a9b2202010-02-26 18:56:32 -08005009 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005010
Christopher Tate6ef58a12009-06-29 14:56:28 -07005011 boolean wasEnabled = mEnabled;
5012 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005013 Settings.Secure.putInt(mContext.getContentResolver(),
5014 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005015 mEnabled = enable;
5016 }
5017
Christopher Tate49401dd2009-07-01 12:34:29 -07005018 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005019 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005020 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005021 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005022 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005023 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005024 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005025
Christopher Tateb6787f22009-07-02 17:40:45 -07005026 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005027
5028 // This also constitutes an opt-out, so we wipe any data for
5029 // this device from the backend. We start that process with
5030 // an alarm in order to guarantee wakelock states.
5031 if (wasEnabled && mProvisioned) {
5032 // NOTE: we currently flush every registered transport, not just
5033 // the currently-active one.
5034 HashSet<String> allTransports;
5035 synchronized (mTransports) {
5036 allTransports = new HashSet<String>(mTransports.keySet());
5037 }
5038 // build the set of transports for which we are posting an init
5039 for (String transport : allTransports) {
5040 recordInitPendingLocked(true, transport);
5041 }
5042 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5043 mRunInitIntent);
5044 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005045 }
5046 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005047 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005048
Christopher Tatecce9da52010-02-03 15:11:15 -08005049 // Enable/disable automatic restore of app data at install time
5050 public void setAutoRestore(boolean doAutoRestore) {
5051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005052 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005053
Joe Onorato8a9b2202010-02-26 18:56:32 -08005054 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005055
5056 synchronized (this) {
5057 Settings.Secure.putInt(mContext.getContentResolver(),
5058 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5059 mAutoRestore = doAutoRestore;
5060 }
5061 }
5062
Christopher Tate8031a3d2009-07-06 16:36:05 -07005063 // Mark the backup service as having been provisioned
5064 public void setBackupProvisioned(boolean available) {
5065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5066 "setBackupProvisioned");
5067
5068 boolean wasProvisioned = mProvisioned;
5069 synchronized (this) {
5070 Settings.Secure.putInt(mContext.getContentResolver(),
5071 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5072 mProvisioned = available;
5073 }
5074
5075 synchronized (mQueueLock) {
5076 if (available && !wasProvisioned && mEnabled) {
5077 // we're now good to go, so start the backup alarms
5078 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5079 } else if (!available) {
5080 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005081 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005082 mAlarmManager.cancel(mRunBackupIntent);
5083 }
5084 }
5085 }
5086
5087 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005088 // We used to use setInexactRepeating(), but that may be linked to
5089 // backups running at :00 more often than not, creating load spikes.
5090 // Schedule at an exact time for now, and also add a bit of "fuzz".
5091
5092 Random random = new Random();
5093 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5094 random.nextInt(FUZZ_MILLIS);
5095 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5096 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005097 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005098 }
5099
Christopher Tate6ef58a12009-06-29 14:56:28 -07005100 // Report whether the backup mechanism is currently enabled
5101 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005102 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005103 return mEnabled; // no need to synchronize just to read it
5104 }
5105
Christopher Tate91717492009-06-26 21:07:13 -07005106 // Report the name of the currently active transport
5107 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005108 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005109 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005110 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005111 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005112 }
5113
Christopher Tate91717492009-06-26 21:07:13 -07005114 // Report all known, available backup transports
5115 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005117
Christopher Tate91717492009-06-26 21:07:13 -07005118 String[] list = null;
5119 ArrayList<String> known = new ArrayList<String>();
5120 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5121 if (entry.getValue() != null) {
5122 known.add(entry.getKey());
5123 }
5124 }
5125
5126 if (known.size() > 0) {
5127 list = new String[known.size()];
5128 known.toArray(list);
5129 }
5130 return list;
5131 }
5132
5133 // Select which transport to use for the next backup operation. If the given
5134 // name is not one of the available transports, no action is taken and the method
5135 // returns null.
5136 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005138
5139 synchronized (mTransports) {
5140 String prevTransport = null;
5141 if (mTransports.get(transport) != null) {
5142 prevTransport = mCurrentTransport;
5143 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005144 Settings.Secure.putString(mContext.getContentResolver(),
5145 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005146 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005147 + " returning " + prevTransport);
5148 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005149 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005150 }
5151 return prevTransport;
5152 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005153 }
5154
Christopher Tatef5e1c292010-12-08 18:40:26 -08005155 // Supply the configuration Intent for the given transport. If the name is not one
5156 // of the available transports, or if the transport does not supply any configuration
5157 // UI, the method returns null.
5158 public Intent getConfigurationIntent(String transportName) {
5159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5160 "getConfigurationIntent");
5161
5162 synchronized (mTransports) {
5163 final IBackupTransport transport = mTransports.get(transportName);
5164 if (transport != null) {
5165 try {
5166 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005167 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005168 + intent);
5169 return intent;
5170 } catch (RemoteException e) {
5171 /* fall through to return null */
5172 }
5173 }
5174 }
5175
5176 return null;
5177 }
5178
5179 // Supply the configuration summary string for the given transport. If the name is
5180 // not one of the available transports, or if the transport does not supply any
5181 // summary / destination string, the method can return null.
5182 //
5183 // This string is used VERBATIM as the summary text of the relevant Settings item!
5184 public String getDestinationString(String transportName) {
5185 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005186 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005187
5188 synchronized (mTransports) {
5189 final IBackupTransport transport = mTransports.get(transportName);
5190 if (transport != null) {
5191 try {
5192 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005193 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005194 return text;
5195 } catch (RemoteException e) {
5196 /* fall through to return null */
5197 }
5198 }
5199 }
5200
5201 return null;
5202 }
5203
Christopher Tate043dadc2009-06-02 16:11:00 -07005204 // Callback: a requested backup agent has been instantiated. This should only
5205 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005206 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005207 synchronized(mAgentConnectLock) {
5208 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005209 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005210 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5211 mConnectedAgent = agent;
5212 mConnecting = false;
5213 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005214 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005215 + " claiming agent connected");
5216 }
5217 mAgentConnectLock.notifyAll();
5218 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005219 }
5220
5221 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5222 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005223 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005224 public void agentDisconnected(String packageName) {
5225 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005226 synchronized(mAgentConnectLock) {
5227 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5228 mConnectedAgent = null;
5229 mConnecting = false;
5230 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005231 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005232 + " claiming agent disconnected");
5233 }
5234 mAgentConnectLock.notifyAll();
5235 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005236 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005237
Christopher Tate1bb69062010-02-19 17:02:12 -08005238 // An application being installed will need a restore pass, then the Package Manager
5239 // will need to be told when the restore is finished.
5240 public void restoreAtInstall(String packageName, int token) {
5241 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005242 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005243 + " attemping install-time restore");
5244 return;
5245 }
5246
5247 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005248 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005249 + " token=" + Integer.toHexString(token));
5250
Christopher Tatef0872722010-02-25 15:22:48 -08005251 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005252 // okay, we're going to attempt a restore of this package from this restore set.
5253 // The eventual message back into the Package Manager to run the post-install
5254 // steps for 'token' will be issued from the restore handling code.
5255
5256 // We can use a synthetic PackageInfo here because:
5257 // 1. We know it's valid, since the Package Manager supplied the name
5258 // 2. Only the packageName field will be used by the restore code
5259 PackageInfo pkg = new PackageInfo();
5260 pkg.packageName = packageName;
5261
5262 mWakelock.acquire();
5263 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5264 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005265 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005266 mBackupHandler.sendMessage(msg);
5267 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005268 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5269 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005270 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005271 try {
5272 mPackageManagerBinder.finishPackageInstall(token);
5273 } catch (RemoteException e) { /* can't happen */ }
5274 }
5275 }
5276
Christopher Tate8c850b72009-06-07 19:33:20 -07005277 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005278 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5279 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5280 + " transport=" + transport);
5281
5282 boolean needPermission = true;
5283 if (transport == null) {
5284 transport = mCurrentTransport;
5285
5286 if (packageName != null) {
5287 PackageInfo app = null;
5288 try {
5289 app = mPackageManager.getPackageInfo(packageName, 0);
5290 } catch (NameNotFoundException nnf) {
5291 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5292 throw new IllegalArgumentException("Package " + packageName + " not found");
5293 }
5294
5295 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5296 // So: using the current active transport, and the caller has asked
5297 // that its own package will be restored. In this narrow use case
5298 // we do not require the caller to hold the permission.
5299 needPermission = false;
5300 }
5301 }
5302 }
5303
5304 if (needPermission) {
5305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5306 "beginRestoreSession");
5307 } else {
5308 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5309 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005310
5311 synchronized(this) {
5312 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005313 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005314 return null;
5315 }
Chris Tate44ab8452010-11-16 15:10:49 -08005316 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005317 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005318 }
5319 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005320 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005321
Christopher Tate73a3cb32010-12-13 18:27:26 -08005322 void clearRestoreSession(ActiveRestoreSession currentSession) {
5323 synchronized(this) {
5324 if (currentSession != mActiveRestoreSession) {
5325 Slog.e(TAG, "ending non-current restore session");
5326 } else {
5327 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5328 mActiveRestoreSession = null;
5329 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5330 }
5331 }
5332 }
5333
Christopher Tate44a27902010-01-27 17:15:49 -08005334 // Note that a currently-active backup agent has notified us that it has
5335 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005336 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005337 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005338 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5339 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005340 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005341 op = mCurrentOperations.get(token);
5342 if (op != null) {
5343 op.state = OP_ACKNOWLEDGED;
5344 }
Christopher Tate44a27902010-01-27 17:15:49 -08005345 mCurrentOpLock.notifyAll();
5346 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005347
5348 // The completion callback, if any, is invoked on the handler
5349 if (op != null && op.callback != null) {
5350 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5351 mBackupHandler.sendMessage(msg);
5352 }
Christopher Tate44a27902010-01-27 17:15:49 -08005353 }
5354
Christopher Tate9b3905c2009-06-08 15:24:01 -07005355 // ----- Restore session -----
5356
Christopher Tate80202c82010-01-25 19:37:47 -08005357 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005358 private static final String TAG = "RestoreSession";
5359
Chris Tate44ab8452010-11-16 15:10:49 -08005360 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005361 private IBackupTransport mRestoreTransport = null;
5362 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005363 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005364
Chris Tate44ab8452010-11-16 15:10:49 -08005365 ActiveRestoreSession(String packageName, String transport) {
5366 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005367 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005368 }
5369
5370 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005371 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005372 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005373 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005374 if (observer == null) {
5375 throw new IllegalArgumentException("Observer must not be null");
5376 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005377
Christopher Tate73a3cb32010-12-13 18:27:26 -08005378 if (mEnded) {
5379 throw new IllegalStateException("Restore session already ended");
5380 }
5381
Christopher Tate1bb69062010-02-19 17:02:12 -08005382 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005383 try {
Christopher Tate43383042009-07-13 15:17:13 -07005384 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005385 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005386 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005387 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005388 // spin off the transport request to our service thread
5389 mWakelock.acquire();
5390 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5391 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5392 mBackupHandler.sendMessage(msg);
5393 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005394 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005395 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005396 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005397 } finally {
5398 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005399 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005400 }
5401
Christopher Tate84725812010-02-04 15:52:40 -08005402 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005403 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5404 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005405
Chris Tate44ab8452010-11-16 15:10:49 -08005406 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005407 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005408
Christopher Tate73a3cb32010-12-13 18:27:26 -08005409 if (mEnded) {
5410 throw new IllegalStateException("Restore session already ended");
5411 }
5412
Dan Egnor0084da52009-07-29 12:57:16 -07005413 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005414 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5415 return -1;
5416 }
5417
5418 if (mPackageName != null) {
5419 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005420 return -1;
5421 }
5422
Christopher Tate21ab6a52009-09-24 18:01:46 -07005423 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005424 for (int i = 0; i < mRestoreSets.length; i++) {
5425 if (token == mRestoreSets[i].token) {
5426 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005427 mWakelock.acquire();
5428 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005429 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005430 mBackupHandler.sendMessage(msg);
5431 Binder.restoreCallingIdentity(oldId);
5432 return 0;
5433 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005434 }
5435 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005436
Joe Onorato8a9b2202010-02-26 18:56:32 -08005437 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005438 return -1;
5439 }
5440
Christopher Tate284f1bb2011-07-07 14:31:18 -07005441 public synchronized int restoreSome(long token, IRestoreObserver observer,
5442 String[] packages) {
5443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5444 "performRestore");
5445
5446 if (DEBUG) {
5447 StringBuilder b = new StringBuilder(128);
5448 b.append("restoreSome token=");
5449 b.append(Long.toHexString(token));
5450 b.append(" observer=");
5451 b.append(observer.toString());
5452 b.append(" packages=");
5453 if (packages == null) {
5454 b.append("null");
5455 } else {
5456 b.append('{');
5457 boolean first = true;
5458 for (String s : packages) {
5459 if (!first) {
5460 b.append(", ");
5461 } else first = false;
5462 b.append(s);
5463 }
5464 b.append('}');
5465 }
5466 Slog.d(TAG, b.toString());
5467 }
5468
5469 if (mEnded) {
5470 throw new IllegalStateException("Restore session already ended");
5471 }
5472
5473 if (mRestoreTransport == null || mRestoreSets == null) {
5474 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5475 return -1;
5476 }
5477
5478 if (mPackageName != null) {
5479 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5480 return -1;
5481 }
5482
5483 synchronized (mQueueLock) {
5484 for (int i = 0; i < mRestoreSets.length; i++) {
5485 if (token == mRestoreSets[i].token) {
5486 long oldId = Binder.clearCallingIdentity();
5487 mWakelock.acquire();
5488 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5489 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5490 packages, true);
5491 mBackupHandler.sendMessage(msg);
5492 Binder.restoreCallingIdentity(oldId);
5493 return 0;
5494 }
5495 }
5496 }
5497
5498 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5499 return -1;
5500 }
5501
Christopher Tate84725812010-02-04 15:52:40 -08005502 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005503 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005504
Christopher Tate73a3cb32010-12-13 18:27:26 -08005505 if (mEnded) {
5506 throw new IllegalStateException("Restore session already ended");
5507 }
5508
Chris Tate44ab8452010-11-16 15:10:49 -08005509 if (mPackageName != null) {
5510 if (! mPackageName.equals(packageName)) {
5511 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5512 + " on session for package " + mPackageName);
5513 return -1;
5514 }
5515 }
5516
Christopher Tate84725812010-02-04 15:52:40 -08005517 PackageInfo app = null;
5518 try {
5519 app = mPackageManager.getPackageInfo(packageName, 0);
5520 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005521 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005522 return -1;
5523 }
5524
5525 // If the caller is not privileged and is not coming from the target
5526 // app's uid, throw a permission exception back to the caller.
5527 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5528 Binder.getCallingPid(), Binder.getCallingUid());
5529 if ((perm == PackageManager.PERMISSION_DENIED) &&
5530 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005531 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005532 + " or calling uid=" + Binder.getCallingUid());
5533 throw new SecurityException("No permission to restore other packages");
5534 }
5535
Christopher Tate7d411a32010-02-26 11:27:08 -08005536 // If the package has no backup agent, we obviously cannot proceed
5537 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005538 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005539 return -1;
5540 }
5541
Christopher Tate84725812010-02-04 15:52:40 -08005542 // So far so good; we're allowed to try to restore this package. Now
5543 // check whether there is data for it in the current dataset, falling back
5544 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005545 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005546
5547 // If we didn't come up with a place to look -- no ancestral dataset and
5548 // the app has never been backed up from this device -- there's nothing
5549 // to do but return failure.
5550 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005551 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005552 return -1;
5553 }
5554
5555 // Ready to go: enqueue the restore request and claim success
5556 long oldId = Binder.clearCallingIdentity();
5557 mWakelock.acquire();
5558 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005559 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005560 mBackupHandler.sendMessage(msg);
5561 Binder.restoreCallingIdentity(oldId);
5562 return 0;
5563 }
5564
Christopher Tate73a3cb32010-12-13 18:27:26 -08005565 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5566 class EndRestoreRunnable implements Runnable {
5567 BackupManagerService mBackupManager;
5568 ActiveRestoreSession mSession;
5569
5570 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5571 mBackupManager = manager;
5572 mSession = session;
5573 }
5574
5575 public void run() {
5576 // clean up the session's bookkeeping
5577 synchronized (mSession) {
5578 try {
5579 if (mSession.mRestoreTransport != null) {
5580 mSession.mRestoreTransport.finishRestore();
5581 }
5582 } catch (Exception e) {
5583 Slog.e(TAG, "Error in finishRestore", e);
5584 } finally {
5585 mSession.mRestoreTransport = null;
5586 mSession.mEnded = true;
5587 }
5588 }
5589
5590 // clean up the BackupManagerService side of the bookkeeping
5591 // and cancel any pending timeout message
5592 mBackupManager.clearRestoreSession(mSession);
5593 }
5594 }
5595
Dan Egnor0084da52009-07-29 12:57:16 -07005596 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005597 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005598
Christopher Tate73a3cb32010-12-13 18:27:26 -08005599 if (mEnded) {
5600 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005601 }
5602
Christopher Tate73a3cb32010-12-13 18:27:26 -08005603 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005604 }
5605 }
5606
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005607 @Override
5608 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005609 long identityToken = Binder.clearCallingIdentity();
5610 try {
5611 dumpInternal(pw);
5612 } finally {
5613 Binder.restoreCallingIdentity(identityToken);
5614 }
5615 }
5616
5617 private void dumpInternal(PrintWriter pw) {
Christopher Tateb8491bb2011-09-29 15:13:11 -07005618 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5619 != PackageManager.PERMISSION_GRANTED) {
5620 pw.println("Permission Denial: can't dump Backup Manager service from from pid="
5621 + Binder.getCallingPid()
5622 + ", uid=" + Binder.getCallingUid()
5623 + " without permission "
5624 + android.Manifest.permission.DUMP);
5625 return;
5626 }
5627
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005628 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005629 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005630 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005631 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005632 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005633 pw.println("Last backup pass: " + mLastBackupPass
5634 + " (now = " + System.currentTimeMillis() + ')');
5635 pw.println(" next scheduled: " + mNextBackupPass);
5636
Christopher Tate91717492009-06-26 21:07:13 -07005637 pw.println("Available transports:");
5638 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005639 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5640 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005641 IBackupTransport transport = getTransport(t);
5642 File dir = new File(mBaseStateDir, transport.transportDirName());
5643 pw.println(" destination: " + transport.currentDestinationString());
5644 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005645 for (File f : dir.listFiles()) {
5646 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5647 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005648 } catch (Exception e) {
5649 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005650 pw.println(" Error: " + e);
5651 }
Christopher Tate91717492009-06-26 21:07:13 -07005652 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005653
5654 pw.println("Pending init: " + mPendingInits.size());
5655 for (String s : mPendingInits) {
5656 pw.println(" " + s);
5657 }
5658
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005659 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005660 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005661 for (int i=0; i<N; i++) {
5662 int uid = mBackupParticipants.keyAt(i);
5663 pw.print(" uid: ");
5664 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005665 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5666 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005667 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005668 }
5669 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005670
Christopher Tateb49ceb32010-02-08 16:22:24 -08005671 pw.println("Ancestral packages: "
5672 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005673 if (mAncestralPackages != null) {
5674 for (String pkg : mAncestralPackages) {
5675 pw.println(" " + pkg);
5676 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005677 }
5678
Christopher Tate73e02522009-07-15 14:18:26 -07005679 pw.println("Ever backed up: " + mEverStoredApps.size());
5680 for (String pkg : mEverStoredApps) {
5681 pw.println(" " + pkg);
5682 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005683
5684 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005685 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005686 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005687 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005688 }
5689 }
Christopher Tate487529a2009-04-29 14:03:25 -07005690}